How do I make shelve file empty in python?
Asked Answered
T

6

11

I have created a shelve file and inserted a dictionary data. Now I want to cleanup that shelve file to reuse as a clean file.

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.
Tommi answered 27/6, 2013 at 11:2 Comment(2)
Why not just delete the file?Baliol
Note that dict = { "foo" : "bar"} should be dict["foo"] = "bar". As it is now, it doesn't insert data into the shelf object - instead it points dict to a new dictionary object while leaving the shelf unchanged.Wandawander
W
17

Shelve behaves just like a dictionary, thus:

dict.clear()

Alternatively, you can always remove the file and let shelve create a new one.

Woman answered 27/6, 2013 at 11:5 Comment(2)
The shelve module is allowed to add stuff to the filename you give it, and on my machine it actually creates a couple files. Clearing the dictionary seems easier as it steers clear of the question of what file or files to delete.Ballocks
The most simplest explanation. ThanksFame
W
8

dict.clear() is the easiest, and should be valid, but seems to not actually clear the shelf files (Python 3.5.2, Windows 7 64-bit). For example, the shelf .dat file size grows every time I run the following snippet, while I would expect it to always have the same size:

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

Update: dbm.dumb, which shelve uses as its underlying database under Windows, contains this TODO item in its code:

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

This explains the ever-growing shelf file problem.


So instead of dict.clear(), I'm using shelve.open with flag='n'. Quoting shelve.open() documentation:

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

And dbm.open() documentation for flag='n':

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

If the shelf is already open, the usage would be:

shelf.close()
shelf = shelve.open('shelf', flag='n')
Wandawander answered 7/2, 2017 at 16:46 Comment(1)
6 1/2 years later and this is still the best way.Domicile
I
1

none of these really work What I ended up doing was creating a function to handle the file deletion.

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()
Interlaken answered 2/4, 2017 at 22:47 Comment(1)
This would have worked as well: # Delete all keywords (key in the mcbShelf) elif sys.argv[1].lower() == 'delete': for keyword in list(mcbShelf.keys()): del mcbShelf[keyword]Thackeray
R
0

I think this is what you're looking for.

if os.path.isfile(mcbShelf):
   os.remove(mcbShelf)
Ransack answered 1/6, 2020 at 13:25 Comment(1)
remove file or empty the file?Consensual
M
0

You can also use a for loop to remove content from shelf:

for key in shelf.keys():
            del shelf[key]
Masjid answered 11/12, 2020 at 22:0 Comment(0)
F
-1

I think this is what you're looking for.

del dict["foo"]
Folger answered 3/2, 2015 at 21:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.