对元组(内存)进行编码以进行导出



我有一个具有不同值的列表。它看起来像这样:

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 和其他东西)。但最主要的是它需要很长时间,我的蟒蛇几乎崩溃了。

有没有更好的方法,或者我应该只更改导出方法?

(现在使用 CSV 工具和写行)

如果您使用的是python 2.X,则可以使用以下python在其文档中建议的unicode_writer类:

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函数。

最新更新