1. 程式人生 > >python之shelve模塊

python之shelve模塊

expect exist ack war sts 方法 delete expec 二進制

1、shevle簡介

  利用 shelve 模塊, 你可以將 Python 程序中的變量保存到二進制的 shelf 文件中。這樣, 程序就可以從硬盤中恢復變量的數據。 shelve 模塊讓你在程序中添加“保存”和“打開” 功能。例如, 如果運行一個程序,並輸入了一些配置設置,就可以將這些設置保存到一個 shelf 文件,然後讓程序下一次運行時加載它們。

2、方法

2.1、寫入數據

import shelve
import datetime
d = shelve.open(shelve_test)  
cats = ["Zophie", "Pooka", "Simon"]
d["cats
"] = cats d[date] = datetime.datetime.now() d.close()

2.2、讀取數據

import shelve
d = shelve.open("shelve_test") # 打開一個文件
print(d["cats"])
print(d["date"])

3、實例

import shelve
d = shelve.open("shelve_data") # open -- file may get suffix added by low-level library

key = "you"
data = 250

d[key] = 250 #
store data at key (overwrites old data if using an existing key) data = d[key] # retrieve a COPY of data at key (raise KeyError if no such key) del d[key] # delete data stored at key (raises KeyError if no such key) flag = key in d # true if the key exists klist = list(d.keys()) # a list of all existing keys (slow!)
# as d was opened WITHOUT writeback=True, beware: d[xx] = [0, 1, 2] # this works as expected, but... d[xx].append(3) # *this doesn‘t!* -- d[‘xx‘] is STILL [0, 1, 2]! # having opened d without writeback=True, you need to code carefully: temp = d[xx] # extracts the copy temp.append(5) # mutates the copy d[xx] = temp # stores the copy right back, to persist it # or, d=shelve.open(filename,writeback=True) would let you just code # d[‘xx‘].append(5) and have it work as expected, BUT it would also # consume more memory and make the d.close() operation slower. d.close()

python之shelve模塊