How to make shelve file empty in python?

I created a shelf file and inserted dictionary data. Now I want to clear this shelf file for 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. 
+6
source share
4 answers

Shelve behaves exactly like a dictionary, in this way:

 dict.clear() 

In addition, you can always delete a file and let the shelf create a new one.

+9
source

dict.clear() is the simplest and should be valid, but apparently doesn't actually clear the shelf files (Python 3.5.2, Windows 7 64-bit). For example, the size of the .dat shelf file grows every time I run the following snippet, while I expect it to always be the same size:

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

Update: dbm.dumb , which shelve uses as the base database for Windows, contains this TODO element in its code :

  • return free space (currently the space occupied by deleted or extended items is never reused)

This explains the ever-growing problem with files in shelves.


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

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

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

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

If the shelf is already open, use will be:

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

None of this really works. As a result, I created a function to handle 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() 
0
source

I think this is what you are looking for.

 del dict["foo"] 
-1
source

Source: https://habr.com/ru/post/948215/


All Articles