In Python, how do I read in a binary file and loop over each byte of that file?
If the file is not too big that holding it in memory is a problem:
with open("filename", "rb") as f:
bytes_read = f.read()
for b in bytes_read:
process_byte(b)
where process_byte represents some operation you want to perform on the passed-in byte.
If you want to process a chunk at a time:
with open("filename", "rb") as f:
bytes_read = f.read(CHUNKSIZE)
while bytes_read:
for b in bytes_read:
process_byte(b)
bytes_read = f.read(CHUNKSIZE)
The with
statement is available in Python 2.5 and greater.