在python中如何使搁置文件为空?
我已经创建了一个搁置文件并插入了一个字典数据。现在我想清理这个搁置文件,以便作为一个干净的文件重新使用在python中如何使搁置文件为空?,python,shelve,Python,Shelve,我已经创建了一个搁置文件并插入了一个字典数据。现在我想清理这个搁置文件,以便作为一个干净的文件重新使用 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. Shelve的行为就像一本字典
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.
Shelve的行为就像一本字典,因此:
dict.clear()
或者,您可以随时删除该文件,并让shelve创建一个新文件。我想这就是您要找的
del dict["foo"]
if os.path.isfile(mcbShelf):
os.remove(mcbShelf)
dict.clear()
是最简单的,应该是有效的,但似乎没有实际清除工具架文件(Python 3.5.2,Windows 7 64位)。例如,每当我运行以下代码段时,shelf.dat
文件大小都会增加,而我希望它始终具有相同的大小:
shelf = shelve.open('shelf')
shelf.clear()
shelf['0'] = list(range(10000))
shelf.close()
更新:
dbm.dumb
,shelve
在Windows下用作其基础数据库,其中包含以下待办事项:
- 回收可用空间(当前,被删除或扩展的项目占用的空间永远不会被重用)
因此,我使用的不是
dict.clear()
,而是shelve.open
和flag='n'
。引述:
可选标志参数与标志具有相同的解释
dbm.open()的参数
对于flag='n'
:
始终创建一个新的空数据库,打开以进行读写
如果搁板已经打开,则用途如下:
shelf.close()
shelf = shelve.open('shelf', flag='n')
所有这些都不起作用,我最终做的是创建一个函数来处理文件删除
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()
我想这就是你要找的
del dict["foo"]
if os.path.isfile(mcbShelf):
os.remove(mcbShelf)
您还可以使用for循环从工具架中删除内容:
for key in shelf.keys():
del shelf[key]
为什么不直接删除这个文件呢?请注意,
dict={“foo”:“bar”}
应该是dict[“foo”]=“bar”
。现在,它不会将数据插入工具架对象,而是将dict
指向一个新的字典对象,同时保持工具架不变。允许shelve
模块向您提供的文件名添加内容,在我的机器上,它实际上创建了两个文件。清除字典似乎更容易,因为它避开了删除哪些文件的问题。这是最简单的解释。感谢此操作也会起作用:#删除所有关键字(在mcbShelf中输入)elif sys.argv[1]。lower()==“Delete”:对于列表中的关键字(mcbShelf.keys()):del mcbShelf[keyword]删除文件还是清空文件?