1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

>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.
I agree with you. I just figured a quote from the documentation would solidify your point.
@mgilson: Fair enough. I will edit to include the appropriate excerpt.
I just did a quick test and it doesn't seem to work. After reading the header (without closing the buffer), I tried b.fromfile(file) and print b.to01(). The print is empty. I just edited my post so you can have an idea of the code I tested.
Strange, works fine here. Odd how bitarray.fromfile() isn't a classmethod though.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.