ite*_*ory 6 python io text utf-16 python-3.x
我需要解析一个文件,它有一个 UTF-16 文本头,后面直接跟二进制数据。为了能够读取二进制数据,我以“rb”模式打开文件,然后,为了读取标题,将其包装到 io.TextIOWrapper() 中。
问题是,当我执行对象的.readline()
方法时TextIOWrapper
,包装器读得太远了(即使我只请求了一行),然后在遇到二进制部分时遇到了 UTF-16 解码错误:AUnicodeDecodeError
被引发。
但是,我需要正确解析文本数据,不能简单地先进行二进制读取,然后再执行 data.find(b"\n\0") 因为不能保证这实际上以偶数偏移量匹配(可能是中途中间字符)。我想避免自己进行 UTF-16 解析。
有没有一种简单的方法可以告诉TextIOWrapper
不要提前阅读?
不,您不能使用TextIOWrapper()
对象,因为它会从更大的块中的底层缓冲区中读取,而不仅仅是行中,所以是的,它会尝试解码第一行之后的二进制数据。你无法阻止这一点。
对于使用行分隔符的单行文本\n
,您实际上不需要使用TextIOWrapper()
. 二进制文件仍然支持逐行读取,其中file.readline()
将为您提供直到下一个\n
字节的二进制数据。只需以二进制方式打开文件,然后读取一行即可。
有效的 UTF-16 数据将始终具有偶数长度。但是,由于 UTF-16 有两种风格:大端字节顺序和小端字节顺序,因此您需要检查读取了多少数据以了解使用了哪些字节顺序,以便有条件地读取应属于第一行数据。如果使用 UTF-16 小尾数法,则保证您读取了奇数个字节,因为换行符被编码为0a 00
而不是,00 0a
并且调用将在文件流中.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
Run Code Online (Sandbox Code Playgroud)
一个演示,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'
Run Code Online (Sandbox Code Playgroud)
仍然可以使用的任何替代实现TextIOWrapper()
都需要在二进制文件和TextIOWrapper()
实例之间放置一个中间包装器,以防止TextIOWrapper()
读取太远,这会很快变得复杂,并且需要包装器了解所使用的编解码器。对于单行文本来说,这是不值得付出努力的。