Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top