1

There is a command in DBM module to delete the value stored at a key.

del d[key]      # delete data stored at key (raises KeyError   # if no such key)

But I cannot even iterate with this command, because the Runtime error occurs.(RuntimeError: dictionary changed size during iteration.)

import dbm
db=dbm.open("file.db","c")
for key in db:
    del db[key]
print(len(db))
db.close()

Is there an efficient way to empty DMB file at once? I am using Python 3.3

Sashko Kopyl
  • 71
  • 1
  • 1
  • 8

1 Answers1

2
for key in list(db):
    del db[key]

should work.

EDIT: If the goal is just to empty the database completely, you can also close the database and re-open it with dbm.open('filename', 'n'). The 'n' flag means "Always create a new, empty database, open for reading and writing"; it seems to override any previously-existing file.

Armin Rigo
  • 12,048
  • 37
  • 48
  • Thank you it works! Are there any solutions without iteration? Deleting files with OS.REMOVE is also an option, but DMB created 2 files. Aren't there a smart way like a DBM.CLEAR() or something? – Sashko Kopyl May 20 '13 at 13:07
  • I have tried it with "n" flag, but it does not override the file. >>> db=dbm.open("db","c") >>> db["line"]=("somedata") >>> db.close() >>> db=dbm.open("db","n") >>> data=db["line"] >>> print(data) b'somedata' >>> db.close() – Sashko Kopyl May 21 '13 at 12:17
  • 1
    Strange, it does for me (Python 2.7.3 on 32-bit Linux). – Armin Rigo May 21 '13 at 21:03
  • Maybe it is a Python version problem. I am using Python 3.3.2 32-bit on Windows7. If flag "n" does not override the file, there is no need for it, because a new file can be created with "c" flag. – Sashko Kopyl May 22 '13 at 00:37
  • 1
    Ah, found it. It's really buried in the docs :-( On Windows, it will use this: http://docs.python.org/3/library/dbm.html#module-dbm.dumb which documents its flag as ignored. I'd still file a bug report if I were you, saying that either the docs at http://docs.python.org/3/library/dbm.html#dbm.open should include a warning, or dumbdbm should be fixed. – Armin Rigo May 22 '13 at 06:52