Python:持久化及字符串


pickle
pickle.dump(obj, file[, protocol])
序列化对象,并将结果数据流写入到文件对象中。参数protocol是序列化模式,默认值为0,表示以文本的形式序列化。protocol的值还可以是1或2,表示以二进制的形式序列化。
pickle.load(file)
反序列化对象。将文件中的数据解析为一个Python对象。
import pickle
a = {'name':'Lee','age':22}
with open(r"C:\Users\Administrator\Desktop\test.txt",'wb') as file:
pickle.dump(a,file)
with open(r"C:\Users\Administrator\Desktop\test.txt",'rb') as file2:
t = pickle.load(file2)
print(t)
>{'name': 'Lee', 'age': 22}
shelve
import shelve
a = {'name': 'zhangsan', 'age': '45'}
b = {'book': '12$', 'clothes': '45$'}
#储存#
with shelve.open(r"C:\Users\Administrator\Desktop\test.dat") as f:
f['info'] = a
f['shop'] = b
##获取
f2 = shelve.open(r"C:\Users\Administrator\Desktop\test.dat")
aa = f2.get('info')
bb = f2.get('shop')
print(aa)
print(bb)
>{'name': 'zhangsan', 'age': '45'}
>{'book': '12$', 'clothes': '45$'}


本文详细介绍了Python中两种数据持久化方法:pickle和shelve。通过实例演示了如何使用pickle进行对象的序列化和反序列化,以及如何利用shelve实现类似字典的键值对存储,方便数据的读取和管理。
8337

被折叠的 条评论
为什么被折叠?



