我正在使用 Python 3.4 中的 pickle.dump 函数将信息保存到一个文件中。我正在尝试以 LIFO(后进先出)形式读取数据。
或者,我在想也许有一种方法我可以只阅读最后一项,假设有一种方法可以直接指向它。然后再次指向它并将其从文件中删除,然后再阅读下一项。
提前致谢!
请您参考如下方法:
您可以保留项目的索引并以新顺序阅读它们:
import pickle
data = ["this", "is", "your", "data"]
indices = [] # keep the index
with open("file_name.p", "wb") as f:
for value in data:
indices.append(f.tell())
pickle.dump(value, f)
# you may want to store `indices` to files
# and read it in again
new_data = []
with open("file_name.p", "rb") as f:
for ap in indices[::-1]:
f.seek(ap)
new_data.append(pickle.load(f))
print(new_data)
