[英]Writing CSV file with umlauts causing “UnicodeEncodeError: 'ascii' codec can't encode character”
I am trying to write characters with double dots (umlauts) such as ä, ö and Ö. 我试图用ä,ö和Ö等双点(变音符)书写字符。 I am able to write it to the file with data.encode("utf-8")
but the result b'\\xc3\\xa4\\xc3\\xa4\\xc3\\x96'
is not nice (UTF-8 as literal characters). 我可以使用data.encode("utf-8")
将其写入文件,但是结果b'\\xc3\\xa4\\xc3\\xa4\\xc3\\x96'
不好(UTF-8为原义字符)。 I want to get "ääÖ"
as written stored to a file. 我想获取写入文件中的"ääÖ"
。
How can I write data with umlaut characters to a CSV file in Python 3? 如何在Python 3中将带有变音符号的数据写入CSV文件?
import csv
data="ääÖ"
with open("test.csv", "w") as fp:
a = csv.writer(fp, delimiter=";")
data=resultFile
a.writerows(data)
Traceback: 追溯:
File "<ipython-input-280-73b1f615929e>", line 5, in <module>
a.writerows(data)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 15: ordinal not in range(128)
Add a parameter encoding
to the open()
and set it to 'utf8'
. 将参数encoding
添加到open()
并将其设置为'utf8'
。
import csv
data = "ääÖ"
with open("test.csv", 'w', encoding='utf8') as fp:
a = csv.writer(fp, delimiter=";")
a.writerows(data)
Edit: Removed the use of io
library as open
is same as io.open
in Python 3. 编辑:删除了io
库的使用,因为open
与Python 3中的io.open
相同。
This solution should work on both python2 and 3 (not needed in python3): 此解决方案应在python2和3上都可以使用(python3不需要):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
data="ääÖ"
with open("test.csv", "w") as fp:
a = csv.writer(fp, delimiter=";")
a.writerows(data)
Credits to: Working with utf-8 encoding in Python source 感谢: 在Python源代码中使用utf-8编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.