如何读取泡菜文件? [英] How to read pickle file?

查看:68
本文介绍了如何读取泡菜文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一些数据,并将其存储了几次,如下所示:

I created some data and stored it several times like this:

with open('filename', 'a') as f:
        pickle.dump(data, f)

每次文件大小都会增加,但是当我打开文件时

Every time the size of file increased, but when I open file

with open('filename', 'rb') as f:
    x = pickle.load(f)

我只能看到上次的数据. 如何正确读取文件?

I can see only data from the last time. How can I correctly read file?

推荐答案

Pickle一次序列化一个对象,然后读回一个对象- 腌制后的数据按顺序记录在文件上.

Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.

如果只是执行pickle.load,则应该读取序列化到文件中的第一个对象(而不是您编写的最后一个对象).

If you simply do pickle.load you should be reading the first object serialized into the file (not the last one as you've written).

反序列化第一个对象后,文件指针位于开始位置 下一个对象的内容-如果您再次简单地调用pickle.load,它将读取下一个对象-直到文件结尾.

After unserializing the first object, the file-pointer is at the beggining of the next object - if you simply call pickle.load again, it will read that next object - do that until the end of the file.

objects = []
with (open("myfile", "rb")) as openfile:
    while True:
        try:
            objects.append(pickle.load(openfile))
        except EOFError:
            break

这篇关于如何读取泡菜文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆