在pickle文件中保存和加载多个对象? [英] Saving and loading multiple objects in pickle file?

查看:98
本文介绍了在pickle文件中保存和加载多个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课,为游戏中的玩家提供服务,创建他们以及其他东西.

I have a class that serves players in a game, creates them and other things.

我需要将这些播放器对象保存在文件中,以便以后使用.我已经尝试过pickle模块,但是我不知道如何保存多个对象并再次加载它们?有没有办法做到这一点,还是应该使用其他类(例如列表)并将对象保存并加载到列表中?

I need to save these player objects in a file to use it later. I've tried the pickle module but I don't know how to save multiple objects and again loading them? Is there a way to do that or should I use other classes such as lists and save and load my objects in a list?

有更好的方法吗?

推荐答案

到目前为止,使用列表,元组或字典是最常见的方法:

Using a list, tuple, or dict is by far the most common way to do this:

import pickle
PIK = "pickle.dat"

data = ["A", "b", "C", "d"]
with open(PIK, "wb") as f:
    pickle.dump(data, f)
with open(PIK, "rb") as f:
    print pickle.load(f)

打印:

['A', 'b', 'C', 'd']

但是,泡菜文件 可以包含任意数量的泡菜.这是产生相同输出的代码.但是请注意,它很难编写和理解:

However, a pickle file can contain any number of pickles. Here's code producing the same output. But note that it's harder to write and to understand:

with open(PIK, "wb") as f:
    pickle.dump(len(data), f)
    for value in data:
        pickle.dump(value, f)
data2 = []
with open(PIK, "rb") as f:
    for _ in range(pickle.load(f)):
        data2.append(pickle.load(f))
print data2

如果执行此操作,则有责任知道所写出的文件中有多少个泡菜.上面的代码通过首先腌制列表对象的数量来做到这一点.

If you do this, you're responsible for knowing how many pickles are in the file you write out. The code above does that by pickling the number of list objects first.

这篇关于在pickle文件中保存和加载多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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