How do you erase the 3 shelve files in python 3?
Asked Answered
S

2

6

I wrote a few unittests with shelve at http://code.google.com/p/filecache/ and python 2 saves exactly the filename I specifiy in shelve.open() but in python 3 I get 3 different files "bak", "dat" and "dir". So before the tests start I want to erase these files but I don't know if I have any guarantee as to their filename or extension.

How can I erase a shelve if I know it's name?

Scruff answered 11/2, 2011 at 8:15 Comment(0)
R
8

What extensions you get depends on which database backend is used. It's possible that the default differs between Python 2 and Python 3, but it can also be a difference between what database interfaces are available in your environment.

So no, you don't have a guarantee to the extensions, unless you use a specific implementation, ie either BsdDbShelf or DbfilenameShelf. You could probably specify a file in a temporary directory created by tempfile, and then delete the while directory.

Racial answered 11/2, 2011 at 8:51 Comment(6)
Kind of strange that I can programatically create a shelf though I can't erase one (without assuming too much).Scruff
@ubershmekel: Yeah, I guess a method to do that would make sense.Racial
DbfilenameShelf doesn't guarantee the filename btw. My current shelf is suppoed to end with '.cache' so the solution I'm using is to just erase all the possible files that end with '.cache', '.cache.bak', '.cache.dir' and '.cache.dat'. Thanks for the help anyhow.Scruff
@ubershmekel: I'm pretty sure the name-endings DbfilenameShelf uses are a limited set of filenames, so that you can see those as guaranteed. It won't create files called ".gif" or ".uggabugga". :)Racial
I would have preferred it if these suffixes were well documented. I'm accepting the solution because of the temporary directory idea, I think that's the most stable solution.Scruff
@ubershmekel: I'm sure they are well documented in the documentation for the database engines that shelf uses.Racial
F
2

I use shelve because tempFile and dict[] objects cannot persist across modules. As you have discovered, calling .clear() does not clear content from the persistent object on disk, leaving a populated r+w file on disk after exit. (Similar to a use-after-free vulnerability) You can delete the shelve when finished using:

import os
import shelve

shelve_name = 'shelve_name'
shelve_contents = shelve.open(shelve_name, flag='c', protocol=None, writeback=False)

shelve_file = (os.path.join(os.getcwd(), shelve_name))
os.remove(shelve_file)
Fillian answered 16/3, 2017 at 18:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.