我正在尝试读取一个文件,当我读取它时,我收到一个 unicode 错误。
def reading_File(self,text):
url_text = "Text1.txt"
with open(url_text) as f:
content = f.read()
错误:
content = f.read()# Read the whole file
File "/home/soft/anaconda/lib/python3.6/encodings/ascii.py", line 26, in
decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 404:
ordinal not in range(128)
为什么会发生这种情况?我试图在Linux系统上运行相同的程序,但在Windows上它运行正常。
最佳答案
根据问题,
i'm trying to run the same on Linux system, but on Windows it runs properly.
由于我们从问题和其他一些答案中知道该文件的内容既不是 ASCII 也不是 UTF-8,因此可以合理猜测该文件是使用 Windows 上常见的 8 位编码之一进行编码的。
碰巧 0x92
映射到 cp125* 编码中的字符“右单引号”,用于美国和拉丁/欧洲地区。
所以文件可能应该这样打开:
# Python3
with open(url_text, encoding='cp1252') as f:
content = f.read()
# Python2
import codecs
with codecs.open(url_text, encoding='cp1252') as f:
content = f.read()
关于python - 由于 python 中的 unicode 错误而无法读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52419117/