Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
简单来说,如下代码:
f.write(u'Río Negro')
引发以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 1: ordinal not in range(128)
我能做些什么? 我正在使用 Python 2.7.3。
open从模块中使用codecs将消除您手动编码的需要:
open
codecs
import codecs with codecs.open('file.txt', 'w', encoding='utf-8') as f: f.write(u'Río Negro')
在 Python 3 中,此功能内置于标准open函数中:
with open('file.txt', 'w', encoding='utf-8') as f: f.write(u'Río Negro')
您需要对字符串进行编码。尝试这个:
f.write(u'Río Negro'.encode('utf-8'))