2

I have got some datas remaining when I delete an element in a shelve. I tried with pop, del and clear but the result is the same. Datas remaining are in file with the dat extension. So, even after using the method clear the size of the dat file isn't 0Ko.

That's what I tryed :

import shelve
test = shelve.open('test')
test['a']=1
#test.pop('a')
#del test['a']
#test.clear()
test.close()

Is there a way to completely remove a data of a shelve ?

Morgan
  • 589
  • 9
  • 20
  • Open the shelve as a file and call `.truncate()`? – Wayne Werner May 04 '16 at 13:59
  • @WayneWerner That true that I can easily completely clean the file with `truncate`. But if I just want to remove completely and properly one unique data that will be harder. – Morgan May 04 '16 at 13:59

2 Answers2

5

You can delete object from shelve by del d[key] it is correct way. But when you delete all objects in you shelve it means that there is empty dict. So your shelve file contains pickled empty dict in this reason sile size isn't 0.

0

Removing all of the data in the shelve is different than removing all of the data in the file.

Apparently shelve creates a database file that (at least for me) is around 13k with no data in it. Try the following:

import os
import shelve

with shelve.open('fnord') as db:
    db['color'] = 'blue, no yelloowwwww!'
    print(list(db.keys()))

print(os.stat('fnord').st_size)

with shelve.open('fnord') as db:
    db.clear()
    print(list(db.keys()))

print(os.stat('fnord').st_size)

You'll see that your shelve has no keys, but it's still got size. If you edit your file with a hex editor, you'll see that there's plenty of data, but it probably has something to do with the database file format.

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
  • I tried it and the problem is the same. I understood that the file size will never be 0k but the thing that I don't understand is why the size of the file still growing each time I execute your script ? That shouldn't be always almost 13k ? – Morgan May 04 '16 at 14:37