当尝试使用下面的代码在@columns中写入数据时,我收到以下错误: " UnicodeEncodeError:' ascii'编解码器不能对字符u' \ xc4'进行编码。位置2:序数不在范围内(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)
答案 0 :(得分:1)
你必须在python doc
中使用UnicodeWriter
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
的完整说明