Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python bitarray to and from file

I'm 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 attempt to read this data back using:

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

it fails with 'bits' being a NoneType. What am i doing wrong?

like image 536
nnachefski Avatar asked Jun 07 '11 13:06

nnachefski


1 Answers

I think "a" is what you want. a.fromfile(fh) is a method which fills a with the contents of fh: it doesn't return a 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')
like image 53
DSM Avatar answered Sep 30 '22 11:09

DSM