Try using the bytearray type (Python 2.6 and later), it's much better suited to dealing with byte data. Your try block would be just:
ba = bytearray(fh.read())
for byte in ba:
print byte & 1
or to create a list of results:
low_bit_list = [byte & 1 for byte in bytearray(fh.read())]
This works because when you index a bytearray you just get back an integer (0-255), whereas if you just read a byte from the file you get back a single character string and so need to use ord to convert it to an integer.
If your file is too big to comfortably hold in memory (though I'm guessing it isn't) then an mmap could be used to create the bytearray from a buffer:
import mmap
m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
ba = bytearray(m)
Answer from Scott Griffiths on Stack OverflowTry using the bytearray type (Python 2.6 and later), it's much better suited to dealing with byte data. Your try block would be just:
ba = bytearray(fh.read())
for byte in ba:
print byte & 1
or to create a list of results:
low_bit_list = [byte & 1 for byte in bytearray(fh.read())]
This works because when you index a bytearray you just get back an integer (0-255), whereas if you just read a byte from the file you get back a single character string and so need to use ord to convert it to an integer.
If your file is too big to comfortably hold in memory (though I'm guessing it isn't) then an mmap could be used to create the bytearray from a buffer:
import mmap
m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
ba = bytearray(m)
You want to use ord instead of int:
if (ord(byte) & 0x01) == 0x01:
Python workflow for reading binary file into byte array
Whats a good way of writing an -int- as BYTES into a binary file (and later, reading it in too) ?
How to Read Binary File in Python?
Trying to read a binary file into an array one byte at a time and get the indexes of any matching sequences
Lets say I have two ints 35400, 364. I need to write these into a binary file one after the other.
How do you do write that int , and how do you open that file and read those ints in later?
(Using Path. if possible)