Som*_*DOS 17 python csv encoding utf-8
我无法在Python中创建utf-8 csv文件.
我正在尝试阅读它的文档,并在示例部分中说:
对于所有其他编码,可以使用以下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)
Run Code Online (Sandbox Code Playgroud)
我一直收到这个错误:
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)
Run Code Online (Sandbox Code Playgroud)
有人可以给我一个灯,所以我可以理解我到底做错了什么,因为我在调用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)
Run Code Online (Sandbox Code Playgroud)
Tam*_*más 14
你不必使用codecs.open; UnicodeWriter接受Unicode输入并负责将所有内容编码为UTF-8.当您UnicodeWriter写入传递给它的文件句柄时,所有内容都已经采用UTF-8编码(因此它适用于您打开的普通文件open).
通过使用codecs.open,您基本上将您的Unicode对象转换为UTF-8字符串UnicodeWriter,然后尝试再次将这些字符串重新编码为UTF-8,就像这些字符串包含Unicode字符串一样,这显然会失败.
| 归档时间: |
|
| 查看次数: |
19594 次 |
| 最近记录: |