gpt4 book ai didi

python - 在 Python 中读取 BSON 文件?

转载 作者:IT老高 更新时间:2023-10-28 13:18:36 26 4
gpt4 key购买 nike

我想在 Python 中读取 BSON 格式的 Mongo 转储并处理数据。我正在使用 Python bson package (我更喜欢使用它而不是拥有 pymongo 依赖项),但它没有解释如何从文件中读取。

这就是我正在尝试的:

bson_file = open('statistics.bson', 'rb')
b = bson.loads(bson_file)
print b[0]

但我明白了:

Traceback (most recent call last):
File "test.py", line 11, in <module>
b = bson.loads(bson_file)
File "/Library/Python/2.7/site-packages/bson/__init__.py", line 75, in loads
return decode_document(data, 0)[1]
File "/Library/Python/2.7/site-packages/bson/codec.py", line 235, in decode_document
length = struct.unpack("<i", data[base:base + 4])[0]
TypeError: 'file' object has no attribute '__getitem__'

我做错了什么?

最佳答案

我发现这适用于我的 mongodb 2.4 BSON 文件和 PyMongo 的“bson”模块:

import bson
with open('survey.bson','rb') as f:
data = bson.decode_all(f.read())

这会返回与存储在该 mongo 集合中的 JSON 文档相匹配的字典列表。

f.read() 数据在 BSON 中如下所示:

>>> rawdata[:100]
'\x04\x01\x00\x00\x12_id\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02_type\x00\x07\x00\x00\x00simple\x00\tchanged\x00\xd0\xbb\xb2\x9eI\x01\x00\x00\tcreated\x00\xd0L\xdcfI\x01\x00\x00\x02description\x00\x14\x00\x00\x00testing the bu'

关于python - 在 Python 中读取 BSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27527982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com