Python 3如何将以null结尾的字符串转换为列表?

4

当你在一个二进制文件中有一些字符串时,Python 3使整个文件读取过程变得非常复杂。

如果我确定读取的是ascii文本,则可以使用string.decode('ascii'),但是在我的文件中,我有以null ('\x00')结束的字符串,我必须读取并转换为字符串列表。没有逐字节检查它是否为null,应该如何完成这项工作?

mylist = chunkFromFile.split('\x00')

TypeError: Type str doesn't support the buffer API
1个回答

7

我猜测chunkFromFile是一个bytes对象。那么你还需要提供一个bytes参数给.split()方法:

mylist = chunkFromFile.split(b'\x00')

请参见:

>>> 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接