因此,我试图用一个csv表创建一个包含unicode字符的表:
with open('test1.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
[writer.writerow(r) for r in table]
但是,每当我试图运行我的程序时,我都会得到这个错误:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 8-10: ordinal not in range(128)
我该怎么解决这个问题?
发布于 2015-09-30 16:25:32
假设您使用的是Python2:
with open('test1.csv', 'wb') as csvfile:
writer = csv.writer(csvfile)
for r in table:
writer.writerow([x.encode('utf-8') for x in r])
当然,在打开csv文件时,还需要使用相同的编码对其进行解码:
with open('test1.csv') as csvfile:
reader = csv.reader(csvfile.decode('utf-8'))
(注意:如果您使用Python3,所有这些都是不必要的-您最初的示例会很好地工作)。
发布于 2015-09-30 15:34:26
首先,不需要使用列表理解来编写csv文件;其次,如果使用python 2.X
,可以使用codecs
模块以正确的编码打开文件;如果使用python3.x,则可以在open
函数中使用encoding
参数。
还请注意,由于write
方法使用了默认编码,如果仍然有unicode错误,则可以在write
方法中使用str.encode()
方法。
Python2.x:
import codecs
with codecs.open(filename, 'w', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
for r in table:
writer.writerow(r.encode('utf-8'))
Python3.x:
with open(filename, 'wb', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
for r in table:
writer.writerow(r.encode('utf-8'))
https://stackoverflow.com/questions/32870044
复制相似问题