10

我创建了一个搁置文件并插入了一个字典数据。现在我想清理搁置文件以作为干净文件重用。

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.
4

6 回答 6

16

Shelve 的行为就像字典一样,因此:

dict.clear()

或者,您可以随时删除文件并让 shelve 创建一个新文件。

于 2013-06-27T11:05:55.403 回答
3

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在 Windows下shelve用作其底层数据库的更新:在其代码中包含此 TODO 项:

  • 回收可用空间(目前,曾经被删除或扩展的项目占用的空间永远不会重复使用)

这解释了不断增长的货架文件问题。


因此dict.clear(),我使用shelve.openwith而不是flag='n'。引用shelve.open()文档

可选标志参数与 dbm.open() 的标志参数具有相同的解释。

dbm.open()文档flag='n':_

始终创建一个新的空数据库,以供读写

如果架子已经打开,用法将是:

shelf.close()
shelf = shelve.open('shelf', flag='n')
于 2017-02-07T16:46:13.307 回答
1

这些都没有真正起作用我最终做的是创建一个函数来处理文件删除。

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()
于 2017-04-02T22:47:25.283 回答
0

我想这就是你要找的。

if os.path.isfile(mcbShelf):
   os.remove(mcbShelf)
于 2020-06-01T13:25:10.310 回答
0

您还可以使用 for 循环从架子上删除内容:

for key in shelf.keys():
            del shelf[key]
于 2020-12-11T22:00:07.613 回答
-1

我想这就是你要找的。

del dict["foo"]
于 2015-02-03T21:14:27.127 回答