【发布时间】:2010-06-21 13:58:24
【问题描述】:
我无法在 Python 中创建 utf-8 csv 文件。
我正在尝试阅读它的文档,在 examples section 中,它说:
对于所有其他编码,以下 UnicodeReader 和 UnicodeWriter 可以使用类。他们采取 在他们的附加编码参数 构造函数并确保 数据通过真正的读者或作者 编码为 UTF-8:
好的。所以我有这个代码:
values = (unicode("Ñ", "utf-8"), unicode("é", "utf-8"))
f = codecs.open('eggs.csv', 'w', encoding="utf-8")
writer = UnicodeWriter(f)
writer.writerow(values)
我不断收到此错误:
line 159, in writerow
self.stream.write(data)
File "/usr/lib/python2.6/codecs.py", line 686, in write
return self.writer.write(data)
File "/usr/lib/python2.6/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 22: ordinal not in range(128)
有人可以给我一个灯,这样我就可以理解我到底做错了什么,因为我在调用 UnicodeWriter 类之前设置了所有的编码?
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
【问题讨论】:
-
发现问题出在 codecs.open 上。当我删除它并使用 open 时,它可以工作。为什么?