shelve是python中的一个模块,它提供了一个简单的数据存储方案,它可以存储字典类型的数据到本地磁盘,通过key来访问,而且它会对数据进行加密。
(1)代码
import shelve
"""
#字典类型的数据dic1
dic1 = {
"101": {"id": "101", "name": "刘备", "height": 178, "phone": "029111"},
"102": {"id": "102", "name": "张飞", "height": 175, "phone": "029222"},
"103": {"id": "103", "name": "关羽", "height": 185, "phone": "029333"},
"104": {"id": "104", "name": "曹操", "height": 180, "phone": "029444"}
}
"""
# 把dic1写入shelve文件
# 打开,其中shelve_dic是将要生成的文件名
db = shelve.open("E:/Python_Code/work/shelve_dic")
#写入
db["101"] = {"id":"101","name":"刘备","height":178,"phone":"029111"}
db["102"] = {"id":"102","name":"张飞","height":175,"phone":"029222"}
db["103"] = {"id":"103","name":"关羽","height":185,"phone":"029333"}
db["104"] = {"id":"104","name":"曹操","height":180,"phone":"029444"}
#关闭
db.close()
(2)运行,可以看到生成了三个文件,数据在.dat文件中,它已经加密了。
(1)代码
import shelve
# 从shelve文件中读取数据
db = shelve.open('E:/Python_Code/work/shelve_dic')
print(db['101']['name'])
print(db['102']['phone'])
#关闭
db.close()
(2)输出
刘备
029222
(1)代码
import shelve
#从shelve文件中读取数据
db = shelve.open('E:/Python_Code/work/shelve_dic')
print(db['101']['name'])
#修改,这里采用了一个缓冲变量stem来修改
stem = db['101']
stem['name'] = "刘皇叔"
db['101'] = stem
#修改后
print(db['101']['name'])
#关闭
db.close()
(2)输出
刘备
刘皇叔