且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在泡菜文件中保存和加载多个对象?

更新时间:2023-12-01 23:03:10

使用列表、元组或字典是迄今为止最常见的方法:

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.