到目前为止,使用列表,元组或字典是最常见的方法:
import picklePIK = "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']
但是,泡菜文件可以包含任意数量的泡菜。这是产生相同输出的代码。但是请注意,它很难编写和理解:
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
如果这样做,你有责任知道所写出的文件中有多少个泡菜。上面的代码通过首先腌制列表对象的数量来做到这一点。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)