[英]Python: ascii codec u'\xe8 when writing list of lists
I am trying to write to file a list of lists, when I try to convert my list of lists to string i get an encoding error. 我试图将列表列表写入文件,当我尝试将列表列表转换为字符串时遇到编码错误。
value contains a list of list like the following: 值包含一个列表列表,如下所示:
[[fsdé,fsdqè,fdsq],[foo1,foo2,foo3]]
Here is my code: 这是我的代码:
f = open('workfile', 'w')
f.write("\n".join("\t".join(map(str,l)) for l in value))
and here is the error: 这是错误:
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)
SOLUTION 解
with io.open("somefile.txt", "w") as fout: fout.write(u"\n".join("\t".join(map(str,l)) for l in value))
using Python 3 module and specifying "u" before the string ! 使用Python 3模块并在字符串前面指定“ u”! AMEN
阿门
Ok, you need to join strings containing accented characters and then write them to files. 好的,您需要连接包含重音符号的字符串 ,然后将它们写入文件。 As you try to convert them using str and as you get an
UnicodeEncodeError
I assume that l is an list of list of unicode
. 当您尝试使用str转换它们并获得
UnicodeEncodeError
我假设l是unicode
列表的列表。
You can simply try to process everything in unicode: 您可以简单地尝试以unicode处理所有内容:
f.write((u"\n".join(u"\t".join(l) for l in value)).encode(encoding))
where encoding could be latin1
, utf8
, cp1252
or whatever is the encoding that you want to use for your file. 其中编码可以是
latin1
, utf8
, cp1252
或您要用于文件的编码。
Alternatively, you can encode the individual strings: 另外,您可以编码单个字符串:
f.write("\n".join("\t".join(map((lambda x: x.encode('utf8')), l)) for l in value))
Python 3 will do this for you. Python 3将为您完成此任务。
In Python 2, you can use Python 3's io module like so: 在Python 2中,您可以像这样使用Python 3的io模块:
with io.open("somefile.txt", "w") as fout: fout.write(u"\N{EURO SIGN}")
You can specify encoding=...
explicitly to io.open
or as I did here, I relied on default, which is locale.getpreferredencoding()
您可以显式地指定
io.open
encoding=...
,或者像我在这里所做的那样,我依赖于默认值locale.getpreferredencoding()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.