當蟒蛇打開文件,我得到的錯誤:打開文件在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) –