【问题标题】:python bitarray to and from filepython bitarray 到和从文件
【发布时间】:2011-09-10 02:44:51
【问题描述】:

我正在使用此代码将一个大的位数组写入文件:

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

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

但是,当我尝试使用以下方法读取此数据时:

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

它失败了,'bits' 是一个 NoneType。我做错了什么?

【问题讨论】:

  • 尝试调试一下。是写作失败还是阅读失败?文件是否存在并写入后包含数据?

标签: python bitarray fromfile


【解决方案1】:

我认为“a”是你想要的。 a.fromfile(fh) 是一种用 fh 的内容填充 a 的方法:它不返回位数组。

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

【讨论】:

  • 注意:似乎bitarray在保存到文件之前先通过附加零转换为字节
【解决方案2】:

我认为 fromfile() 方法不会返回任何内容。这些值存储在您的位数组“a”中。

【讨论】: