Python3逐行读取混合文本/二进制数据

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

我需要解析一个具有UTF-16文本标题并直接跟随二进制数据的文件。为了能够读取二进制数据,我以“rb”模式打开文件,然后,为了读取标题,将其包装到io.TextIOWrapper()中。

问题是,当我执行.readline()对象的TextIOWrapper方法时,包装器向前读取太远(即使我只请求一行),然后在遇到二进制部分时遇到UTF-16解码错误:a UnicodeDecodeError is提高。

但是,我需要正确解析文本数据并且不能简单地先进行二进制读取,然后执行data.find(b“\ n \ 0”),因为它不能保证这实际上匹配均匀偏移(可能是中途中间人物)。我想避免自己做UTF-16解析。

是否有一种简单的方法可以告诉TextIOWrapper不要提前阅读?

python python-3.x text io utf-16
1个回答
0
投票

不,你不能使用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解码错误对于'二进制数据',之后我们再次读取文本和数据:

>>> 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()读取太多,这将变得复杂快,并且需要包装器知道所使用的编解码器。对于单行文本,这是不值得的。

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