【问题标题】:Python3 reading mixed text/binary data line-by-linePython3逐行读取混合文本/二进制数据
【发布时间】:2019-02-11 12:25:47
【问题描述】:

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

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

但是,我需要正确解析文本数据,不能简单地先进行二进制读取,然后再执行 data.find(b"\n\0"),因为不能保证这实际上在偶数偏移处匹配(可能在字符之间)。我想避免自己进行 UTF-16 解析。

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

【问题讨论】:

  • 这是什么文件?

标签: python python-3.x text io utf-16


【解决方案1】:

不,您不能使用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 little-endian 数据(使用 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() 读得太远,这会变得复杂快 并且要求包装器了解所使用的编解码器。对于单行文本,这是不值得的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2019-09-25
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多