【问题标题】:Python gives unicode error when writing to filePython 写入文件时出现 unicode 错误
【发布时间】:2018-02-18 13:30:19
【问题描述】:

我正在尝试写入文件。

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 作为我的编辑器。

有人知道发生了什么吗?

【问题讨论】:

  • 您的代码对我来说可以正常工作(MacOS 上的 Python 3.6.1)。您是否在系统上设置了与编码相关的异常环境变量?我没有设置,你不应该需要它们。如果您在软件中正确处理编码/解码,您也不应该需要 PYTHONIOENCODING(我建议不要使用这种拐杖)。

标签: python-3.x file unicode io


【解决方案1】:

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

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

【讨论】:

  • 工作出色!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
相关资源
最近更新 更多