我使用Python 3.4中的pickle.dump函数将信息保存到文件中。我试图读取LIFO(后进先出)表格中的数据。
替代方案,我想也许有一种方法可以读取最后一项,假设有一种方法可以直接指向它。然后再次指向它并在读取下一个项目之前将其从文件中删除。
提前致谢!
答案 0 :(得分:1)
您可以保留项目的索引并按新顺序阅读:
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)