7

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?

nnachefski
  • 1,552
  • 2
  • 18
  • 29
  • Try a bit of debugging. Is it the writing or the reading that is failing? Does the file exist and contain data after writing it? – Daniel Roseman Jun 07 '11 at 14:09

2 Answers2

12

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')
DSM
  • 342,061
  • 65
  • 592
  • 494
  • 1
    **Note**: seems that the bitarray is converted to bytes first by appending zeros before saving to the file – zyxue Sep 17 '15 at 17:33
1

I think the fromfile() method doesn't return anything. The values are stored in your bitarray 'a'.

Reto Aebersold
  • 16,306
  • 5
  • 55
  • 74