Python写入文件时出现Unicode错误

3

我试图将数据写入文件中。

filename = "test.txt"
string = "Niñas and niños"

with open(filename, 'w') as element:
            element.write(string)

这会返回以下错误:
"Traceback (most recent call last):
  File "/Users/alex/Documents/Python/filewriter.py", line 5, in <module>
    element.write(string)
UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' 
in position 2: ordinal not in range(128)"

我正在使用最新版本的Python、最新版本的MacOS以及SublimeText3作为我的编辑器。
有人知道发生了什么吗?

你的代码在我的机器上运行良好(Python 3.6.1 on MacOS)。你的系统中是否设置了与编码相关的不寻常环境变量?我没有设置任何环境变量,你也不应该需要它们。如果你在软件中正确处理编码/解码,那么你也不需要PYTHONIOENCODING(我建议不要使用这个支撑)。 - FMc
1个回答

12

使用UTF-8编码打开文件,如下所示:

with open(filename, 'w', encoding='utf-8') as element:

运行得非常出色!谢谢! - Alex Heebs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接