2013-06-27 28 views
6

我創建了一個擱置文件並插入了一個字典數據。現在我想清理該擱置文件以重新用作乾淨的文件。如何使python中的擱置文件爲空?

import shelve 
dict = shelve.open("Sample.db") 
# insert some data into sample.db 
dict = { "foo" : "bar"} 

#Now I want to clean entire shelve file to re-insert the data from begining. 
+0

爲什麼不直接刪除文件? –

+1

注意'dict = {「foo」:「bar」}'應該是'dict [「foo」] =「bar」'。就像現在這樣,它不會將數據插入到貨架對象中,而是將「dict」指向新的字典對象,同時保持貨架不變。 – george

回答

9

擱置的行爲就像一本字典,即:

dict.clear() 

或者,你可以隨時刪除該文件,並讓擱置創建一個新的。

+0

允許'shelve'模塊將東西添加到您提供的文件名中,並且在我的機器上它實際上會創建一對文件。清除字典似乎更容易,因爲它避開了要刪除的文件或文件的問題。 – kuzzooroo

1

dict.clear()是最簡單的,並且應該是有效的,但似乎沒有真正清除文件架子(Python的3.5.2,Windows 7的64位)。例如,貨架.dat文件大小增加每次運行下面的代碼片段的時間,而我希望它總是有相同的尺寸:

shelf = shelve.open('shelf') 
shelf.clear() 
shelf['0'] = list(range(10000)) 
shelf.close() 

更新:dbm.dumb,這shelve用作其Windows下的底層數據庫,包含此TODO項目in its code

  • 回收自由空間(目前,空間一度佔據通過刪除或擴展的項目是從來沒有重複使用)

這解釋了不斷增長的貨架文件問題。


所以不是dict.clear(),我使用shelve.openflag='n'。引用shelve.open() documentation

可選的標誌參數具有相同的解釋dbm.open的標誌 參數()。

而且dbm.open() documentationflag='n'

始終創建一個新的空數據庫,進行讀取和寫入

如果貨架已經打開,用法是:

shelf.close() 
shelf = shelve.open('shelf', flag='n') 
0

這些都不起作用我最終做的是創建一個func以處理文件刪除。

import shelve 
import pyperclip 
import sys 
import os 

mcbShelf = shelve.open('mcb') 
command = sys.argv[1].lower() 

def remove_files(): 
    mcbShelf.close() 
    os.remove('mcb.dat') 
    os.remove('mcb.bak') 
    os.remove('mcb.dir') 

if command == 'save': 
    mcbShelf[sys.argv[2]] = pyperclip.paste() 
elif command == 'list': 
    pyperclip.copy(", ".join(mcbShelf.keys())) 
elif command == 'del': 
    remove_files() 
else: 
    pyperclip.copy(mcbShelf[sys.argv[1]]) 

mcbShelf.close()