python - 由于 python 中的 unicode 错误而无法读取文件

标签 python python-3.x character-encoding python-unicode

我正在尝试读取一个文件,当我读取它时,我收到一个 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/

相关文章:

python - "class MyDict(dict): pass"的用途是什么,它与普通字典有什么不同?

python - 将张量列表转换为张量的张量 pytorch

python-3.x - Beam Streaming 管道不会将文件写入存储桶

python - 尝试为 python 2.7.11 安装 mathplot.lib。但找不到合适的流程。尝试了Youtube教程中的各种方法,但没有成功

python - 如何使用Python获取PE文件的指令?

python - 基于平台创建pythonwheel

html - 特殊 HTML 字符

mysql - PDO 相当于 mysql_client_encoding()?

java - 即使使用 UTF-8,为什么 ¿ 在 Windows 和 Linux 中显示不同?

python - 在 Pandas Python 中连接字符串数据