python 读取带有 FF FE 字节前缀的文本文件

问题描述 投票:0回答:1

我有一个文件,可以在 VSCode 编辑器中作为普通文本文件打开。但如果我尝试用 Python 阅读它:

with open("file.ass") as f:
   for line in f.readlines():
       ...

它会抛出异常:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

如果我尝试用二进制模式打开它,前几个字节读起来像:

f = open("file.ass", "rb")
b = f.read()
print(b[:50])

Out[36]: b'\xff\xfe[\x00S\x00c\x00r\x00i\x00p\x00t\x00 \x00I\x00n\x00f\x00o\x00]\x00\r\x00\n\x00;\x00 \x00S\x00c\x00r\x00i\x00p\x00t\x00 \x00'

如果我这样做

decode('utf-16')
,我就能看到正确的字符。

b[:50].decode('utf-16')
Out[58]: '[Script Info]\r\n; Script '

但我想知道是否有一种更优雅的方法来像处理普通文本文件一样处理此类文件。换句话说,我怎么知道我是否需要像读取普通文本文件一样执行

decode('utf-16')
并使用
readlines()
?谢谢。

python encoding
1个回答
0
投票

打开文件时可以使用

encoding

with open("file.ass", encoding='utf-16') as f:
   for line in f.readlines():
       ...

正如您所说,您的文件在 VSCode 中打开,您可以在 VSCode 底部检查文件的猜测编码:

然后您可以在 Python 中使用相同的编码。

请注意,VSCode 使用

"files.autoGuessEncoding":true
(您可以在设置中查看)。这就是为什么你让它将你的文件作为“普通文本”读取。

© www.soinside.com 2019 - 2024. All rights reserved.