Ale*_*ebs 3 unicode io file python-3.x
我正在尝试写入文件。
filename = "test.txt"
string = "Niñas and niños"
with open(filename, 'w') as element:
element.write(string)
Run Code Online (Sandbox Code Playgroud)
这将返回以下错误:
"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)"
Run Code Online (Sandbox Code Playgroud)
我使用最新版本的 Python、最新版本的 MacOS 和 SublimeText3 作为我的编辑器。
任何人都知道发生了什么?
用utf-8编码打开文件,像这样:
with open(filename, 'w', encoding='utf-8') as element:
Run Code Online (Sandbox Code Playgroud)