shelve

1、 shelve

  • shelve提供python的持久化操做。
  • 持久化:把數據寫到硬盤上
  • shelve操做與字典很是相似
import shelve

d = shelve.open("tom")
d["name"] = "Tom"
print(d["name"])  # Tom
d.close()

文件關閉後沒法讀取其內容python

import shelve

d = shelve.open("tom")
d["name"] = "Tom"
d.close()

print(d["name"])  # ValueError: invalid operation on closed shelf

 遍歷:spa

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()

2、 writeback

  • 把修改的內容自動回寫到文件中

1. 修改內容

shelve.open()默認writeback=False,因此,在默認狀況下修改字典的數據,修改內容不會寫入到文件中:code

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時,修改的數據保存在文件中,再次讀取爲修改後的結果blog

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條件下,刪除內容,文件中內容也會被刪除it

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()  
相關文章
相關標籤/搜索