Il codice di esempio di come leggere Unicode somministrato http://docs.python.org/library/csv.html#examples sembra essere obsoleto, in quanto non funziona con Python 2.6 e 2.7.
Segue il UnicodeDictReader
che funziona con utf-8 e potrebbe essere con altre codifiche, ma l'ho testato solo su utf-8 input.
L'idea, in breve, è decodificare Unicode solo dopo che una riga csv è stata suddivisa in campi da csv.reader
.
class UnicodeCsvReader(object):
def __init__(self, f, encoding="utf-8", **kwargs):
self.csv_reader = csv.reader(f, **kwargs)
self.encoding = encoding
def __iter__(self):
return self
def next(self):
# read and split the csv row into fields
row = self.csv_reader.next()
# now decode
return [unicode(cell, self.encoding) for cell in row]
@property
def line_num(self):
return self.csv_reader.line_num
class UnicodeDictReader(csv.DictReader):
def __init__(self, f, encoding="utf-8", fieldnames=None, **kwds):
csv.DictReader.__init__(self, f, fieldnames=fieldnames, **kwds)
self.reader = UnicodeCsvReader(f, encoding=encoding, **kwds)
Usage (codifica sorgente è utf-8):
csv_lines = (
"абв,123",
"где,456",
)
for row in UnicodeCsvReader(csv_lines):
for col in row:
print(type(col), col)
uscita:
$ python test.py
<type 'unicode'> абв
<type 'unicode'> 123
<type 'unicode'> где
<type 'unicode'> 456
fonte
2011-05-31 12:59:51
Non funziona per me su linux: r = unicode_csv_reader (file ('/ tmp/csv-unicode.csv'). Read(). Split ('\ n')); r.next(). Gives: UnicodeDecodeError: il codec 'ascii' non può decodificare il byte 0xf8 in posizione 14: ordinale non nel range (128) – Parand
neanche per me. Lo stesso errore. –
Lo stesso qui, la risposta di Maxmin qui sotto funziona però:) – bjunix