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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.