4

Python 3 really complicated the whole file reading process, when you have a binary file with some strings in it.

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

1 Answer 1

7

I'm guessing that chunkFromFile is a bytes object. Then you also need to provide a bytes argument to the .split() method:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.