如何在python中使shelve文件为空?

2024-06-02 00:43:00 发布

您现在位置: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.

Tags: 文件to数据sampleimportdbdata字典
3条回答

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

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()

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

dict.clear()

或者,您始终可以删除该文件并让shelve创建一个新文件。

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下用作其基础数据库的,包含这个TODO项in its code

  • reclaim free space (currently, space once occupied by deleted or expanded items is never reused)

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


所以我不是用dict.clear(),而是用shelve.openflag='n'。引用^{} documentation

The optional flag parameter has the same interpretation as the flag parameter of dbm.open().

对于flag='n'^{} documentation

Always create a new, empty database, open for reading and writing

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

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

相关问题 更多 >