【问题标题】:UnicodeEncodeError while writing to CSV写入 CSV 时出现 UnicodeEncodeError
【发布时间】:2014-09-26 15:36:22
【问题描述】:

当尝试使用下面的代码在@columns 中写入数据时,我收到以下错误: "UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 2: ordinal not in range(128)"

我尝试过对 ascii 进行编码/解码,但是...

u'G\xe5ng'.encode('ascii')

... 产生相同的错误消息。关于如何解决这个问题的任何想法?

    writer = csv.writer(out_file, delimiter=';',
                            quotechar='"', quoting=csv.QUOTE_ALL)

    columns = ['Gods', u'G\xe5ng', 'Cykel', 'Buss', 'Bil', u'F\xe4rja', u'Sj\xf6fart', u'T\xe5g/sp\xe5rv\xe4g']


    writer.writerow(columns)

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您必须在 python 文档中使用UnicodeWriter give

    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)
    

    您将在CSV Python Example获得完整的描述

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 2016-12-21
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      相关资源
      最近更新 更多