用 shelve 模組來存資料

Coolest發表於2019-08-31

shelve模組是一個進行資料操作的python模組,如果和pickle,json模組對比,shelve模組用起來更簡單。

隨便寫個要儲存的變數,拿animals列表舉個例子

import shelve
animals = ['cat','dog','lion']
data = shelve.open('test')
data['animal'] = animals
data.close()

首先是匯入了shelve模組,之後再建立了一個animals列表。用data = shelve.open(‘test’)來讀取test,如果test這個資料庫不存在,就建立一個。建立之後,當前的工作目錄就會出現新檔案。因為shelve模組的儲存方式是透過字典儲存,所以shelve模組也能使用update,items這些字典的函式。data[animal] = animals把資料儲存到資料庫裡。最後再用data.close()關閉資料庫。

如果要讀取資料,開啟test資料庫,然後讀取就行了。

opendata = shelve.open('test')
print(opendata['animal'])

返回結果:
['cat','dog','lion']

本作品採用《CC 協議》,轉載必須註明作者和本文連結
coder Derek

相關文章