我习惯使用 JSON 和 Numpy 在 python 中存储数组、列表和字典,但我想使用 BSON,因为浮点数只占用 4 个字节,从而减少文件大小。
使用 Json,我执行以下操作:
import numpy
import json
a = numpy.random.rand(12).reshape((3,4))
with open('out.json', 'w') as out:
json.dump(a.tolist(), out)
with open('out.json') as inp:
b = numpy.array(json.load(inp))
print b
我没有找到一种明显的方法来对 BSON 做同样的事情。我试过这个:
import numpy
from bson import BSON
a = numpy.random.rand(12).reshape((3,4))
b = BSON.encode({'a': a.tolist()})
with open('out.bson', 'wb') as out:
out.write(b)
with open('out.bson', 'rb') as inp:
print BSON().decode(inp.read())
但是得到这个错误:
Traceback (most recent call last):
File "apaga.py", line 12, in <module>
print BSON().decode(inp.read())
File "/usr/lib/python2.7/dist-packages/bson/__init__.py", line 539, in decode
(document, _) = _bson_to_dict(self, as_class, tz_aware)
bson.errors.InvalidBSON: not enough data for a BSON document