python打开csvutf-8报错_用Python创建utf-8csv文件

我不能用Python创建utf-8csv文件。

我试着读一下文档,在examples section里,上面写着:For all other encodings the following

UnicodeReader and UnicodeWriter

classes can be used. They take an

additional encoding parameter in their

constructor and make sure that the

data passes the real reader or writer

encoded as 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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值