[英]Python 3 null terminated string to list?
Python 3 really complicated the whole file reading process, when you have a binary file with some strings in it. 当你有一个包含一些字符串的二进制文件时,Python 3确实使整个文件读取过程变得复杂。
I can do string.decode('ascii')
when I'm sure what I read is ascii text, but in my file I have strings with null ('\\x00')
terminated strings I must read an convert to list of strings. 当我确定我读的是ascii文本时,我可以做
string.decode('ascii')
,但是在我的文件中我有null ('\\x00')
终止字符串的字符串我必须读取转换为字符串列表。 How would be the new way to do it, without going byte-by-byte and checking if it's a null or not? 如何进行新的方法,而不是逐字节地检查它是否为空?
mylist = chunkFromFile.split('\x00')
TypeError: Type str doesn't support the buffer API
I'm guessing that chunkFromFile
is a bytes
object. 我猜测
chunkFromFile
是一个bytes
对象。 Then you also need to provide a bytes
argument to the .split()
method: 然后你还需要为
.split()
方法提供一个bytes
参数:
mylist = chunkFromFile.split(b'\x00')
See: 看到:
>>> 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.