我有一个文件,可以在 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()
?谢谢。