[英]encode tuple (memory) for exporting
我有一个具有不同值的列表。 看起来像这样:
data = [
('Column1', 'Column2'),
('myFirstNovel', 'myAge'),
('mySecondNovel', 'myAge2'),
('myThirdNovel', 'myAge3'),
('myFourthNovel', 'myAge4')
]
将数据写入csv时出现编码错误,因此要在导出之前对数据进行编码。 所以我尝试了这个:
[[all.encode('utf-8') for all in items] for items in data]
现在这并不能真正解决我的问题(数据填充为\\ xe2 \\ x80 \\ x94 \\ xc2 \\ xa0和其他内容)。 但是主要的是它需要很长时间,并且我的python几乎崩溃了。
有更好的方法还是应该只更改导出方法?
(现在使用csv工具和writerows)
如果您使用的是python unicode_writer
,则可以使用以下unicode_writer
类,该类在python文档中建议:
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)
在python 3.x中,您可以简单地将编码传递给open
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.