shelve error
Alex Martelli
aleax at mac.com
Mon Apr 9 10:20:35 EDT 2007
Peter Otten <__peter__ at web.de> wrote:
> Alex Martelli wrote:
>
> > BTW, if you DO want to call shelve.open on a path f that may correspond
> > to an arbitrary existing file (and want to toss away the previous
> > contents of that file, if any) the correct way to call is then:
> >
> > s = shelve.open(whatever_path, 'n')
> >
> > since 'n' truncates an existing file, or creates a new one, as needed.
>
> It's not entirely arbitrary since you get an exception if that file is not a
> valid database:
>
> >>> open("tmp.db", "w").write("garbage")
> >>> import shelve
> >>> shelve.open("tmp.db", "n")
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "/usr/local/lib/python2.5/shelve.py", line 225, in open
> return DbfilenameShelf(filename, flag, protocol, writeback)
> File "/usr/local/lib/python2.5/shelve.py", line 209, in __init__
> Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
> File "/usr/local/lib/python2.5/anydbm.py", line 80, in open
> raise error, "db type could not be determined"
> anydbm.error: db type could not be determined
You're right -- anydbm.open, even when asked to "truncate the file",
still does mandate that the file, if it exists, be in some proper DBM
format (to determine which DBM module it will use to open it). This is
not intuitive, and needs to be mentioned in the Nutshell.
Alex
More information about the Python-list
mailing list