[英]How to write Unicode text into a Python file object
簡單地說,以下代碼:
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。
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'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.