importshelveduring handling of the above exception, another exception occurred:a = shelve.open('1')
b = [1,2,3]
a['b'] =b
a.close()
a['b']
原因是a.close()就已經關閉了shelf檔案。
1 >>> shelve.open('1')['b'
]2 [1,2,3]
3 >>> shelve.close()
4traceback (most recent call last):
5 file "
", line 1, in
6 attributeerror: module '
shelve
' has no attribute '
close
'
shelve模組沒有close(),需要變數來關閉。
那如果沒有關閉會怎樣?
1 >>>b2 [1, 2, 3]
3 >>> c = shelve.open('5'
) 4 >>> c['
b'] =b
5 >>> c['b'
]6 [1, 2, 3] #建立並開啟檔案5
7 >>> d = shelve.open('6'
)8 >>> d['
b'] = [4,5,6]
9 >>> d['b'
]10 [4, 5, 6] #建立並開啟檔案6
11 >>>b
12 [1, 2, 3]
13 >>> c['b'
]14 [1, 2, 3]
15 >>>d.close()
16 >>> d['b'
] #關閉檔案
17traceback (most recent call last):
18 file "
", line 111, in
__getitem__
19 value =self.cache[key]
20 keyerror: 'b'
2122
during handling of the above exception, another exception occurred:
2324
traceback (most recent call last):
25 file "
", line 1, in
26 file "
", line 113, in
__getitem__
27 f =bytesio(self.dict[key.encode(self.keyencoding)])
28 file "
", line 70, in
closed
29raise valueerror('
invalid operation on closed shelf')
30valueerror: invalid operation on closed shelf
31 >>> c['b'
]32 [1, 2, 3]
從上面**可以看出shelve模組的close()是分別針對每個檔案的,會一直處於開啟狀態直到關閉。
1 >>>list(c.values())2 [[1, 2, 3]]
3 >>>list(c.keys())
4 ['b'
]5 >>>list(c)
6 ['b'
]
shelf值預設返回值為keys()方法的返回值。
shelve模組使用
shelve模組是乙個簡單的key,value將記憶體資料通過檔案持久化的模組,可以持久化任何pickle可支援的python資料格式 import shelve data shelve.open shelve file 開啟乙個檔案 info name zhangsan lisi wangwu d...
python模組詳解 shelve
shelve模組是乙個簡單的k,v 將記憶體資料通過檔案持久化的模組,可以持久化任何pickle可以支援的python資料。簡單的說對 pickle的更上一層的封裝。寫檔案import shelve d shelve.open test4 這個檔案不用存在,執行自動生成 name hello chi...
collections模組,shelve模組
1.collections 在內部資料型別的基礎上,加上collections模組提供的額外資料型別 namedtuple,deque,counter 1.1 namedple命名元祖有助於對元祖的每個位置賦予意義 用來產生使用名稱來訪問元元素的資料物件 from collections impor...