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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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()
Strange, it does for me (Python 2.7.3 on 32-bit Linux).
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.
Ah, found it. It's really buried in the docs :-( On Windows, it will use this: 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 docs.python.org/3/library/dbm.html#dbm.open should include a warning, or dumbdbm should be fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.