[英]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.