Python bitarray to and from file

I am writing a large bitarray to a file using this code:

import bitarray
bits = bitarray.bitarray(bin='0000011111') #just an example

with open('somefile.bin', 'wb') as fh:
    bits.tofile(fh)

However, when I try to read this data using:

import bitarray
a = bitarray.bitarray()
with open('somefile.bin', 'rb') as fh:
    bits = a.fromfile(fh)
    print bits

it fails when the “bits” are NoneType. What am I doing wrong?

+3
source share
2 answers

I think "a" is what you want. a.fromfile (fh) is a method that fills content with fh: it does not return bitarray.

>>> import bitarray
>>> bits = bitarray.bitarray('0000011111')
>>> 
>>> print bits
bitarray('0000011111')
>>> 
>>> with open('somefile.bin', 'wb') as fh:
...     bits.tofile(fh)
... 
>>> a = bitarray.bitarray()
>>> with open('somefile.bin', 'rb') as fh:
...     a.fromfile(fh)
... 
>>> print a
bitarray('0000011111000000')
+5
source

I think the fromfile () method returns nothing. Values ​​are stored in your bitrate 'a'.

+1
source

All Articles