- Python 資料持久化教程
- Python 資料持久化 - 首頁
- Python 資料持久化 - 簡介
- Python 資料持久化 - 檔案 API
- 使用 os 模組處理檔案
- Python 資料持久化 - 物件序列化
- Python 資料持久化 - Pickle 模組
- Python 資料持久化 - Marshal 模組
- Python 資料持久化 - Shelve 模組
- Python 資料持久化 - dbm 包
- Python 資料持久化 - CSV 模組
- Python 資料持久化 - JSON 模組
- Python 資料持久化 - XML 解析器
- Python 資料持久化 - Plistlib 模組
- Python 資料持久化 - Sqlite3 模組
- Python 資料持久化 - SQLAlchemy
- Python 資料持久化 - PyMongo 模組
- Python 資料持久化 - Cassandra 驅動程式
- 資料持久化 - ZODB
- 資料持久化 - Openpyxl 模組
- Python 資料持久化資源
- Python 資料持久化 - 快速指南
- Python 資料持久化 - 有用資源
- Python 資料持久化 - 討論
Python 資料持久化 - Shelve 模組
Python 標準庫中的 shelve 模組提供了一種簡單而有效的物件持久化機制。此模組中定義的 shelf 物件是一個類似字典的物件,它持久地儲存在磁碟檔案中。這會建立一個類似於類 UNIX 系統上 dbm 資料庫的檔案。
shelf 字典有一些限制。只有字串資料型別可以用作此特殊字典物件中的鍵,而任何可 pickle 的 Python 物件都可以用作值。
shelve 模組定義了以下三個類:
| 序號 | Shelve 模組及說明 |
|---|---|
| 1 |
Shelf 這是 shelf 實現的基類。它使用類似字典的物件進行初始化。 |
| 2 |
BsdDbShelf 這是 Shelf 類的子類。傳遞給其建構函式的 dict 物件必須支援 first()、next()、previous()、last() 和 set_location() 方法。 |
| 3 |
DbfilenameShelf 這也是 Shelf 的子類,但它接受檔名作為其建構函式的引數,而不是 dict 物件。 |
shelve 模組中定義的 open() 函式返回一個DbfilenameShelf物件。
open(filename, flag='c', protocol=None, writeback=False)
檔名引數分配給建立的資料庫。flag 引數的預設值為“c”,表示讀寫訪問。其他標誌為“w”(只寫)“r”(只讀)和“n”(新的讀寫)。
序列化本身由 pickle 協議控制,預設為 none。最後一個引數 writeback 引數預設為 false。如果設定為 true,則快取訪問的條目。每次訪問都會呼叫 sync() 和 close() 操作,因此過程可能會很慢。
以下程式碼建立了一個數據庫並在其中儲存字典條目。
import shelve
s=shelve.open("test")
s['name']="Ajay"
s['age']=23
s['marks']=75
s.close()
這將在當前目錄中建立 test.dir 檔案,並將鍵值資料以雜湊形式儲存。Shelf 物件具有以下可用方法:
| 序號 | 方法及說明 |
|---|---|
| 1 |
close() 同步並關閉持久字典物件。 |
| 2 |
sync() 如果 shelf 以 writeback 設定為 True 開啟,則寫回快取中的所有條目。 |
| 3 |
get() 返回與鍵關聯的值 |
| 4 |
items() 元組列表 - 每個元組都是鍵值對 |
| 5 |
keys() shelf 鍵的列表 |
| 6 |
pop() 刪除指定的鍵並返回相應的值。 |
| 7 |
update() 從另一個 dict/iterable 更新 shelf |
| 8 |
values() shelf 值的列表 |
要訪問 shelf 中特定鍵的值,請執行以下操作:
s=shelve.open('test')
print (s['age']) #this will print 23
s['age']=25
print (s.get('age')) #this will print 25
s.pop('marks') #this will remove corresponding k-v pair
與內建字典物件一樣,items()、keys() 和 values() 方法返回檢視物件。
print (list(s.items()))
[('name', 'Ajay'), ('age', 25), ('marks', 75)]
print (list(s.keys()))
['name', 'age', 'marks']
print (list(s.values()))
['Ajay', 25, 75]
要將另一個字典的條目與 shelf 合併,請使用 update() 方法。
d={'salary':10000, 'designation':'manager'}
s.update(d)
print (list(s.items()))
[('name', 'Ajay'), ('age', 25), ('salary', 10000), ('designation', 'manager')]