python bitarray to and from file

旧时模样 提交于 2020-01-02 06:18:32

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/6266330/python-bitarray-to-and-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!