6

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

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

它因“位”为无类型而失败。我究竟做错了什么?

4

2 回答 2

10

我认为“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')
于 2011-06-07T14:12:08.077 回答
1

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

于 2011-06-07T14:12:45.677 回答