我在理解读取和写入文件的文本方面有一些大脑故障(Python 2.4)。

# The string, which has an a-acute in it.
ss = u'Capit\xe1n'
ss8 = ss.encode('utf8')
repr(ss), repr(ss8)

(“u’Capit \ xe1n’”、“’Capit \ xc3 \ xa1n’")

print ss, ss8
print >> open('f1','w'), ss8

>>> file('f1').read()
'Capit\xc3\xa1n\n'

于是我在我最喜欢的编辑器f2文件中输入了大写字母\xc3\xa1n。

然后:

>>> open('f1').read()
'Capit\xc3\xa1n\n'
>>> open('f2').read()
'Capit\\xc3\\xa1n\n'
>>> open('f1').read().decode('utf8')
u'Capit\xe1n\n'
>>> open('f2').read().decode('utf8')
u'Capit\\xc3\\xa1n\n'

我哪里不明白了?显然,我忽略了一些至关重要的魔力(或良好的感觉)。在文本文件中输入什么才能得到正确的转换?

我在这里真正搞不懂的是,当它来自外部时,如果你不能让Python识别它,那么UTF-8表示的意义是什么。也许我应该只是JSON转储字符串,并使用它,因为它有一个asciiable表示!更重要的是,当这个Unicode对象从文件中传入时,是否存在Python能够识别和解码的ASCII表示形式?如果有,我怎么得到它?

>>> print simplejson.dumps(ss)
'"Capit\u00e1n"'
>>> print >> file('f3','w'), simplejson.dumps(ss)
>>> simplejson.load(open('f3'))
u'Capit\xe1n'

当前回答

这适用于在Python 3.2中读取UTF-8编码的文件:

import codecs
f = codecs.open('file_name.txt', 'r', 'UTF-8')
for line in f:
    print(line)

其他回答

我找到了最简单的方法,将整个脚本的默认编码改为'UTF-8':

import sys
reload(sys)
sys.setdefaultencoding('utf8')

任何打开、打印或其他语句将只使用utf8。

至少适用于Python 2.7.9。

谢谢到https://markhneedham.com/blog/2015/05/21/python-unicodeencodeerror-ascii-codec-cant-encode-character-uxfc-in-position-11-ordinal-not-in-range128/(看最后)。

这适用于在Python 3.2中读取UTF-8编码的文件:

import codecs
f = codecs.open('file_name.txt', 'r', 'UTF-8')
for line in f:
    print(line)

为了读入Unicode字符串,然后发送到HTML,我这样做:

fileline.decode("utf-8").encode('ascii', 'xmlcharrefreplace')

适用于python支持的http服务器。

除了codecs.open()之外,io.open()可以在这两种情况下使用。X和3。X来读写文本文件。例子:

import io

text = u'á'
encoding = 'utf8'

with io.open('data.txt', 'w', encoding=encoding, newline='\n') as fout:
    fout.write(text)

with io.open('data.txt', 'r', encoding=encoding, newline='\n') as fin:
    text2 = fin.read()

assert text == text2

我试图用Python 2.7.9解析iCal:

从icalendar导入日历

但我得到:

 Traceback (most recent call last):
 File "ical.py", line 92, in parse
    print "{}".format(e[attr])
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 7: ordinal not in range(128)

它只是用:

print "{}".format(e[attr].encode("utf-8"))

(现在它可以打印liké á böss。)