python创建一个csv文件_在Python中创建一个utf-8 csv文件

我无法在Python中创建一个utf-8 csv文件。

我试图阅读它的文档,并在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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值