import shelvedef CreateData(): try: db = shelve.open('shelve_test') # key与value必须是字符串 db['int'] = 1 db['float'] = 2.3 db['string'] = "I like python." db['key'] = 'value' finally: db.close()def LoadData(): #这个可以另外写一个.py文件去读取 db = shelve.open('shelve_test') for item in db.items(): print (item) print(db['int']) print(db['float']) print(db['string']) print(db['key']) db.close()if __name__ == '__main__': CreateData() LoadData()
shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写
pickle 写: 以写方式打开一个文件描述符,调用pickle.dump把对象写进去
import pickledn = {'baidu':'www.baidu.com','qq':'www.qq.com','360':'www.360.cn'}name = ['mayun','mahuateng','liyanhong']f = open('a.txt','wb') #‘wb'用二进制写入pickle.dump(dn,f) ##写一个对象pickle.dump(name,f) ##再写一个对象f.close() 读:以读的方式打开文件描述符,调用pickle.load加载对象f = open('a.txt','rb') #‘wb'用二进制读取pickle.load(f) ##加载一个对象pickle.load(f) ##加载另一个对象f.close()