开发者

python bitarray to and from file

开发者 https://www.devze.com 2023-03-11 11:12 出处:网络
I\'m writing a large bitarray to a file using this code: import bitarray bits = bitarray.bitarray(bin=\'0000011111\') #just an examp开发者_运维知识库le

I'm writing a large bitarray to a file using this code:

import bitarray
bits = bitarray.bitarray(bin='0000011111') #just an examp开发者_运维知识库le

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?


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')


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

0

精彩评论

暂无评论...
验证码 换一张
取 消