Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对用于导出的元组(内存)进行编码_Python_Csv - Fatal编程技术网

Python 对用于导出的元组(内存)进行编码

Python 对用于导出的元组(内存)进行编码,python,csv,Python,Csv,我有一个不同值的列表。看起来是这样的: data = [ ('Column1', 'Column2'), ('myFirstNovel', 'myAge'), ('mySecondNovel', 'myAge2'), ('myThirdNovel', 'myAge3'), ('myFourthNovel', 'myAge4') ] 我在将数据写入csv时遇到编码错误,因此希望在导出之前对数据进行编码。所以我试了一下: [[all.encode('utf-8') for all in items

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

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 2.X,您可以使用python文档中建议的以下
unicode\u 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)

在Python3.X中,您只需将编码传递给函数即可。

我们谈论的列表有多大?另外,包含包含unicode字符串而不是普通字符串的示例数据可能会有所帮助……您是否可以包含更多的代码,以便我们可以在上下文中查看writerows调用?