shelve 模块
shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式
说白了,就是pickle的高级吧
例子:
一.pickle 处理python的数据格式
①pickle_dump.py
#!/usr/bin/env python#coding=utf-8#这个例子是pickle dump对比shelve之持久化import pickleclass Test(object):def __init__(self,n):self.n=nt=Test(123)t2=Test(456)name=["yaobin","test","haha"]f=open("pickle_test.pk1",'wb')pickle.dump(t,f) #把t类dump进去pickle.dump(t2,f) #把t2类dump进去pickle.dump(name,f) #把列表也dump进去f.close()
②pickle_load.py
#!/usr/bin/env python#coding=utf-8#这个例子主要pickle load对比shelve之取值import picklef=open("pickle_test.pk1","rb")#pickle的load 是先dump进去的,先出来,先进先出#第一次loada=pickle.load(f)print(a.n)#第二次loadb=pickle.load(f)print(b.n)#第三次loadc=pickle.load(f)print(c)#总结: 不能随时的load我想要的东西出来啊,所以才有shelve,可以使用key的方式持久化,再通过key取出来。#结果123456['yaobin', 'test', 'haha']
二.shelve 处理python的数据格式
①shelve之持久化.py
#!/usr/bin/env python#coding=utf-8import shelved = shelve.open('shelve_test') #打开一个文件class Test(object):def __init__(self,n):self.n = nt1 = Test(123) #实例化t2 = Test(456) #实例化name = ["alex","rain","test"] #列表d["list"] = name #持久化列表d["t1"] = t1 #持久化类d["t2"] = t2 #持久化类d.close()
②shelve之取值.py
#!/usr/bin/env python#coding=utf-8import shelvea=shelve.open('shelve_test') #打开一个文件#用shelve的get方法取出key对应的值,比pickle load 要好h1=a.get("list")h2=a.get("t1")h3=a.get("t2")print(h1)print(h2.n)print(h3.n)#结果['alex', 'rain', 'test']123456