import pickle
# pickle.dumps() 和 pickle.loads()
test_data = ['Save me!', 123, 'ss', True]
t1=pickle.dumps(test_data)
print(t1)
# b'\x80\x03]q\x00(X\x08\x00\x00\x00Save me!q\x01K{X\x02\x00\x00\x00ssq\x02\x88e.'
t2=pickle.loads(t1)
print(t2)
# ['Save me!', 123, 'ss', True]
# pickle.dump() 和 pickle.load()
test_data = ['Save me!', 123, 'ss', True]
with open('testdata.txt','wb') as f:
pickle.dump(test_data,f)
with open('testdata.txt','rb') as f:
test_data = pickle.load(f)
如果你想保存多个对象,一种方法是把这些对象先全部放在一个序列中,在对这个序列进行存储:
a = 123
b = "hello"
c = 0.618
data = (a, b, c)
...
pickle.dump(data, f)
另一种方法就是依次保存和提取:
...
pickle.dump(a, f)
pickle.dump(b, f)
pickle.dump(c, f)
...
x = pickle.load(f)
y = pickle.load(f)
z = pickle.load(f)
dump 方法可以增加一个可选的参数,来指定用二进制来存储:
pickle.dump(data, f, True)
而 load 方法会自动检测数据是二进制还是文本格式,无需手动指定。