I am trying to read in a binary file in Python. The file consists of a thousands of lines each 2957 bytes long (1 byte boolean followed by 739 4 byte integers)
I have tried this suggestion but this does not work (the program runs forever)
This is my current setup, but I am having troubles iterating over the file:
with open("bin-file", "rb") as f:
for line in f:
# Here I deal with every line
The problem is that every line in the loop is a different length, and the number of lines does not correspond to the actual number of lines in the file. I am assuming Python finds, what it thinks are, end-of-line markers in the binary data, but those do not correspond to the actual ends of the lines.
Another option I tried involves the struct.unpack()
function to unpack line by line, since I know exactly how many bytes are on every line.
import struct
unpack_str = '=?iiiiiiii...' # The actual string contains 739 i's
n_bytes = 2957 # There are 2957 bytes per line
with open("bin-file", "rb") as f:
line_bin = f.read(n_bytes)
line_str = struct.unpack(unpack_str,line_bin)
This works, but only returns the first line. How would I iterate through all of the lines until I hit the EOF, knowing that every line is exactly n_bytes
long?