Python 3 null终止要列出的字符串?

3 python string binary ascii python-3.x

当你有一个包含一些字符串的二进制文件时,Python 3确实使整个文件读取过程变得复杂.

string.decode('ascii')当我确定我读的是ascii文本时,我可以做,但在我的文件中,我有带有空('\x00')终止字符串的字符串我必须读取转换为字符串列表.如何进行新的方法,而不是逐字节地检查它是否为空?

mylist = chunkFromFile.split('\x00')

TypeError: Type str doesn't support the buffer API
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 6

我猜这chunkFromFile是一个bytes对象.然后你还需要为方法提供一个bytes参数.split():

mylist = chunkFromFile.split(b'\x00')
Run Code Online (Sandbox Code Playgroud)

看到:

>>> chunkFromFile = bytes((123,45,0,67,89))
>>> chunkFromFile
b'{-\x00CY'
>>> chunkFromFile.split(b'\x00')
[b'{-', b'CY']
>>> chunkFromFile.split('\x00')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Type str doesn't support the buffer API
Run Code Online (Sandbox Code Playgroud)