在 Python 3 中读取文件时编码错误?
Wrong encoding when reading file in Python 3?
当我读取 python 中的文件并将其打印到屏幕上时,它无法正确读取某些字符,但是,那些硬编码到变量中的相同字符打印得很好。这是一个示例,其中“test.html”包含文本“Hallå”:
with open('test.html','r') as file:
Str = file.read()
print(Str)
Str = "Hallå"
print(Str)
这会生成以下输出:
hallå
Hallå
我的猜测是文件中的数据在读入 Python 时的解释方式有问题,但是我不确定自 Python 3.8 以来它是什么。 5已经默认使用UTF-8编码。
函数 open
不 默认使用 UTF-8。正如 the documentation 所说:
In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False)
is called to get the current locale encoding.
因此,这取决于并且可以肯定的是,您必须自己指定编码。如果文件以 UTF-8 格式保存,您应该这样做:
with open('test.html', 'r', encoding='utf-8') as file:
另一方面,不清楚文件是否以UTF-8编码保存。如果不是,您将不得不选择另一个。
当我读取 python 中的文件并将其打印到屏幕上时,它无法正确读取某些字符,但是,那些硬编码到变量中的相同字符打印得很好。这是一个示例,其中“test.html”包含文本“Hallå”:
with open('test.html','r') as file:
Str = file.read()
print(Str)
Str = "Hallå"
print(Str)
这会生成以下输出:
hallå
Hallå
我的猜测是文件中的数据在读入 Python 时的解释方式有问题,但是我不确定自 Python 3.8 以来它是什么。 5已经默认使用UTF-8编码。
函数 open
不 默认使用 UTF-8。正如 the documentation 所说:
In text mode, if encoding is not specified the encoding used is platform dependent:
locale.getpreferredencoding(False)
is called to get the current locale encoding.
因此,这取决于并且可以肯定的是,您必须自己指定编码。如果文件以 UTF-8 格式保存,您应该这样做:
with open('test.html', 'r', encoding='utf-8') as file:
另一方面,不清楚文件是否以UTF-8编码保存。如果不是,您将不得不选择另一个。