Python 写入CSV时出现UNICODEENCODEER错误

Python 写入CSV时出现UNICODEENCODEER错误,python,python-2.7,Python,Python 2.7,尝试使用下面的代码在@columns中写入数据时,出现以下错误: “UnicodeEncodeError:'ascii'编解码器无法对位置2:序号不在范围(128)中的字符u'\xc4'进行编码” 我已经尝试运行编码/解码到ascii,但是 u'G\xe5ng'.encode('ascii') 。。。产生相同的错误消息。有没有办法解决这个问题 writer = csv.writer(out_file, delimiter=';',

尝试使用下面的代码在@columns中写入数据时,出现以下错误: “UnicodeEncodeError:'ascii'编解码器无法对位置2:序号不在范围(128)中的字符u'\xc4'进行编码”

我已经尝试运行编码/解码到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)

您必须使用
UnicodeWriter
give-in-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)
您将获得有关的完整描述