Python3 读取混合 text/binary 数据 line-by-line

Python3 reading mixed text/binary data line-by-line

我需要解析一个包含 UTF-16 文本 header 并紧跟二进制数据的文件。为了能够读取二进制数据,我以 "rb" 模式打开文件,然后,为了读取 header,将其包装到 io.TextIOWrapper().

问题是当我执行 TextIOWrapper object 的 .readline() 方法时,包装器提前读取太多(即使我只请求了一行)然后遇到二进制部分时遇到 UTF-16 解码错误:引发 UnicodeDecodeError

但是,我需要对文本数据进行适当的解析,不能简单地先进行二进制读取,然后再进行 data.find(b"\n[=26=]"),因为不能保证这确实匹配以均匀的偏移量(可能是中途 in-between 个字符)。我想避免自己进行 UTF-16 解析。

有没有简单的方法告诉 TextIOWrapper 不要提前阅读?

不,你不能使用 TextIOWrapper() 对象,因为它会以更大的块从底层缓冲区读取,而不仅仅是行,所以是的,它会尝试解码超过第一行。你不能阻止它。

对于使用 \n 行分隔符的单行文本,您确实不需要使用 TextIOWrapper()。二进制文件仍然支持逐行读取,其中 file.readline() 将为您提供直到下一个 \n 字节的二进制数据。只需打开文件 为二进制 ,然后读取一行。

有效的 UTF-16 数据总是具有偶数长度。但是因为 UTF-16 有两种风格,大端字节序和小端字节序,所以您需要检查读取了多少数据以查看使用的字节顺序,以便有条件地读取应该属于的单个字节第一行数据。如果使用了 UTF-16 little-endian,则保证您读取的字节数是奇数,因为换行符被编码为 09 00 而不是 00 90 并且 .readline() 调用将离开文件流中的单个 00 字节。那样的话,只要多读一个字节,在解码前加到第一行数据即可:

with open(filename, 'rb') as binfile:
    firstline = binfile.readline()
    if len(firstline) % 2:
        # little-endian UTF-16, add one more byte
        firstline += binfile.read(1)
    text = firstline.decode('utf-16')

    # read binary data from the file

带有 io.BytesIO() 的演示,我们首先编写 UTF-16 小端数据(使用 BOM 指示解码器的字节顺序),文本后跟两个低代理序列导致UTF-16解码错误,代表'binary data',之后我们再次读取文本和数据:

>>> import io, codecs
>>> from pprint import pprint
>>> binfile = io.BytesIO()
>>> utf16le_wrapper = io.TextIOWrapper(binfile, encoding='utf-16-le', write_through=True)
>>> utf16le_wrapper.write('\ufeff')  # write the UTF-16 BOM manually, as the -le and -be variants won't include this
1
>>> utf16le_wrapper.write('The quick brown  jumps over the lazy \n')
40
>>> binfile.write(b'\xDF\xFF\xDF\xFF')  # binary data, guaranteed to not decode as UTF-16
4
>>> binfile.flush()  # flush and seek back to start to move to reading
>>> binfile.seek(0)
0
>>> firstline = binfile.readline()  # read that first line
>>> len(firstline) % 2              # confirm we read an odd number of bytes
1
>>> firstline += binfile.read(1)    # add the expected null byte
>>> pprint(firstline)               # peek at the UTF-16 data we read
(b'\xff\xfeT\x00h\x00e\x00 \x00q\x00u\x00i\x00c\x00k\x00 \x00b\x00r\x00o\x00'
 b'w\x00n\x00 \x00>\xd8\x8a\xdd \x00j\x00u\x00m\x00p\x00s\x00 \x00o\x00v\x00'
 b'e\x00r\x00 \x00t\x00h\x00e\x00 \x00l\x00a\x00z\x00y\x00 \x00=\xd8\x15\xdc'
 b'\n\x00')
>>> print(firstline.decode('utf-16'))  # bom included, so the decoder detects LE vs BE
The quick brown  jumps over the lazy 

>>> binfile.read()
b'\xdf\xff\xdf\xff'

仍然可以使用 TextIOWrapper() 的任何替代实现都需要一个中间包装器位于二进制文件和 TextIOWrapper() 实例之间,以防止 TextIOWrapper() 读得太远,这会变得复杂 fast 并且需要包装器知道所使用的编解码器。对于一行文本,这根本不值得付出努力。