Question

I wrote a program that uses bitarray 0.8.0 to write bits to a binary file. I would like to add a header to this binary file to describe what's inside the file.

My problem is that I think the method "fromfile" of bitarray necessarily starts reading the file from the beginning. I could make a workaround so that the reading program gets the header and then rewrite a temporary file containing only the binary portion (bitarray tofile), but it doesn't sound too efficient of an idea.

Is there any way to do this properly?

My file could look something like the following where clear text is the header and binary data is the bitarray information:

...{(0, 0): '0'}{(0, 0): '0'}{(0, 0): '0'}���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������...

Edit:

I tried the following after reading the response:

bits = ""
b = bitarray()
with open(Filename, 'rb') as file:
    #Get header
    byte = file.read(1)
    while byte != "":
        # read header
        byte = file.read(1)
    b.fromfile(file)
    print b.to01()
    print "len(b.to01())", len(b.to01())

The length is 0 and the print of "to01()" is empty. However, the print of the header is fine.

Était-ce utile?

La solution

My problem is that I think the method "fromfile" of bitarray necessarily starts reading the file from the beginning.

This is likely false; it, like most other file read routines, probably starts at the current position within the file, and stops at EOF.

EDIT:

From the documentation:

fromfile(f, [n])

Read n bytes from the file object f and append them to the bitarray interpreted as machine values. When n is omitted, as many bytes are read until EOF is reached.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top