正如标题所述,我想将一系列对象存储在一个pickle文件中,并从该序列中检索n'th
项目。
以下是执行此操作的代码:
import pickle
import os
filename = 'my_file.pkl'
if os.path.exists(filename):
os.remove(filename)
# Write things to file
things = [{'thing0': 0}, {'thing1': 1}, {'thing2': 2}]
for thing in things:
with open(filename, 'ab') as f:
pickle.dump(thing, f)
def get_nth_item(filename, n):
with open(filename, 'rb') as f:
for i in range(n+1):
obj = pickle.load(f)
return obj
# Read things back
assert get_nth_item(filename, 0) == {'thing0': 0}
assert get_nth_item(filename, 1) == {'thing1': 1}
assert get_nth_item(filename, 2) == {'thing2': 2}
但是它效率很低,因为我必须先扫描整个文件直到那个项目。
是否有一种很好的方法来检索项目而不必先阅读所有先前的项目?