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