Python:编写列表列表时的ascii编解码器u'\ xe8

时间:2015-12-10 13:48:26

标签: python encoding ascii

我正在尝试写入文件列表,当我尝试将列表列表转换为字符串时,我遇到编码错误。

值包含列表列表,如下所示:

[[fsdé,fsdqè,fdsq],[foo1,foo2,foo3]]

这是我的代码:

f = open('workfile', 'w')
f.write("\n".join("\t".join(map(str,l)) for l in value))

这是错误:

Traceback (most recent call last):

  File "<string>", line 1, in <module>

  File "package_list_script.py", line 23, in craft_json

    f.write("\n".join("\t".join(map(str,l)) for l in value))

  File "package_list_script.py", line 23, in <genexpr>

    f.write("\n".join("\t".join(map(str,l)) for l in value))

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 4: ordinal not in range(128)

with io.open("somefile.txt", "w") as fout: fout.write(u"\n".join("\t".join(map(str,l)) for l in value))

使用Python 3模块并在字符串前指定“u”! AMEN

2 个答案:

答案 0 :(得分:1)

好的,您需要加入包含重音字符的字符串,然后将它们写入文件。当您尝试使用str转换它们时,当您得到UnicodeEncodeError时,我假设l是unicode列表的列表。

您可以简单地尝试以unicode处理所有内容:

f.write((u"\n".join(u"\t".join(l) for l in value)).encode(encoding))

其中编码可以是latin1utf8cp1252或您要用于文件的编码。

或者,您可以编码各个字符串:

f.write("\n".join("\t".join(map((lambda x: x.encode('utf8')), l)) for l in value))

答案 1 :(得分:1)

Python 3将为您完成此任务。

在Python 2中,您可以像这样使用Python 3的io模块:

with io.open("somefile.txt", "w") as fout: fout.write(u"\N{EURO SIGN}")

您可以明确指定encoding=... io.open,或者就像我在此处所做的那样,我依赖默认值,即locale.getpreferredencoding()