Python script to convert from UTF-8 to ASCII

Nicolas picture Nicolas · Nov 29, 2010 · Viewed 124.3k times · Source

I'm trying to write a script in python to convert utf-8 files into ASCII files:

#!/usr/bin/env python
# *-* coding: iso-8859-1 *-*

import sys
import os

filePath = "test.lrc"
fichier = open(filePath, "rb")
contentOfFile = fichier.read()
fichier.close()

fichierTemp = open("tempASCII", "w")
fichierTemp.write(contentOfFile.encode("ASCII", 'ignore'))
fichierTemp.close()

When I run this script I have the following error :

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 13: ordinal not in range(128)

I thought that can ignore error with the ignore parameter in the encode method. But it seems not.

I'm open to other ways to convert.

Answer

Utku Zihnioglu picture Utku Zihnioglu · Nov 29, 2010
data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")