一、 shelve shelve提供python的持久化操作。 持久化:把數據寫到硬碟上 shelve操作與字典非常類似 文件關閉後無法讀取其內容 遍歷: 二、 writeback 把修改的內容自動回寫到文件中 1. 修改內容 shelve.open()預設writeback=False,所以,在默 ...
一、 shelve
- shelve提供python的持久化操作。
- 持久化:把數據寫到硬碟上
- shelve操作與字典非常類似
import shelve d = shelve.open("tom") d["name"] = "Tom" print(d["name"]) # Tom d.close()
文件關閉後無法讀取其內容
import shelve d = shelve.open("tom") d["name"] = "Tom" d.close() print(d["name"]) # ValueError: invalid operation on closed shelf
遍歷:
import shelve d = shelve.open("namelist", writeback=True) d["name"] = "Tom" d["age"] = 18 d.close() d = shelve.open("namelist") for k in d: # 遍歷所有的key print(k) # name age for k in d.keys(): # 遍歷所有key print(k) # name age for k, v in d.items(): # 遍歷所有的鍵-值對 print(k, v) # name Tom age 18 d.close()
二、 writeback
- 把修改的內容自動回寫到文件中
1. 修改內容
shelve.open()預設writeback=False,所以,在預設情況下修改字典的數據,修改內容不會寫入到文件中:
import shelve d = shelve.open("namedict") d["one"] = {"name": "Tom", "age": 18, "hobby": "football"} d.close()
import shelve d = shelve.open("namedict") d["one"]["name"] = "Linda" d.close() d = shelve.open("namedict") print(d["one"]) # {'name': 'Tom', 'age': 18, 'hobby': 'football'} d.close()
當writeback=True時,修改的數據保存在文件中,再次讀取為修改後的結果
import shelve d = shelve.open("namedict", writeback=True) d["one"]["name"] = "Linda" d.close() d = shelve.open("namedict") print(d["one"]) # {'name': 'Linda', 'age': 18, 'hobby': 'football'} d.close()
2. 刪除內容
在writeback=True條件下,刪除內容,文件中內容也會被刪除
import shelve d = shelve.open("namedict", writeback=True) del d["one"] d.close() d = shelve.open("namedict") print(d["one"]) # KeyError: b'one' 報錯 d.close()