[英]Python 3 null terminated string to list?
当你有一个包含一些字符串的二进制文件时,Python 3确实使整个文件读取过程变得复杂。
当我确定我读的是ascii文本时,我可以做string.decode('ascii')
,但是在我的文件中我有null ('\\x00')
终止字符串的字符串我必须读取转换为字符串列表。 如何进行新的方法,而不是逐字节地检查它是否为空?
mylist = chunkFromFile.split('\x00')
TypeError: Type str doesn't support the buffer API
我猜测chunkFromFile
是一个bytes
对象。 然后你还需要为.split()
方法提供一个bytes
参数:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.