当蟒蛇打开文件,我得到的错误:打开文件在Python错误
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
我的代码是
p=open("afile.txt","r")
file=p.read()
当蟒蛇打开文件,我得到的错误:打开文件在Python错误
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
我的代码是
p=open("afile.txt","r")
file=p.read()
这是一个UnicodeError。您正尝试使用ASCII编解码器读取Unicode字符。
尝试:
import codecs
p = codecs.open("afile.txt", "r", "utf-8")
f = p.read()
或
import codecs
p = codecs.open("afile.txt", "r", "utf-16")
f = p.read()
你应该也可能考虑使用:
with codecs.open("afile.txt", "r", "utf-8") as f:
# Do whatever you want with f
这使得它能够自动关闭的文件,当您退出with
声明。
你也可以试试iso-8859-15
或cp437
看看https://pypi.python.org/pypi/chardet和https://docs.python.org/3/library/codecs.html#codecs.open。
[UnicodeEncodeError:'ascii'编解码器无法在位置20编码字符u'\ xa0':序号不在范围(128)]中可能的重复(http://stackoverflow.com/questions/9942594/unicodeencodeerror- ascii-codec -cant-encode-character -u-xa0-in-position-20) –