shelve error

Alex Martelli aleax at
Mon Apr 9 04:14:12 CEST 2007

7stud <bbxx789_05ss at> wrote:

> On Apr 4, 10:22 pm, mik3l3... at wrote:
> > how did you generate aaa.txt?
> Ok, I got it to work by supplying a filename that didn't previously
> exist.  Neither the book I am reading, "Beginning Python: From Novice
> to Professional" nor the book I am using as a reference, "Python in
> Nutshell", happens to mention that important fact.

I notice that the Nutshell (2nd ed) has a small errata that may be
what's confusing you. On p. 284, under "The shelve module", I say:

shelve supplies a function open that is polymorphic to .

On p. 286, you find the whole page explaining (which is why
I didn't want to duplicate all that info), including the detail that the
default value for argument flag is 'r' (meaning read-only operation, and
on a file that must already exist).  However, is not
_entirely_ polymorphic to, in this small but crucial detail:
the defaulf value for argument flag is 'c' (meaning, as p. 286 correctly
says, that it creates a new file if it doesn't exist, but also accepts
and opens an existing file, and operation is read-write).

Of course, if the existing file was not created by the shelve module,
there may well be errors -- shelve uses DBM-like archive files, as
clearly explained on p. 284, not arbitrary text files (nor for that
matter arbitrary binary files).  As the documentation for
explicitly says, it's all about DBM files; adding "will not work right
if you try to open just any random textfile or other file you may happen
to have laying around on your favourite storage device" would be
insulting to the reader and a waste of space, so I don't consider it a
valid errata.

But if you open an errata for the missing explanation for the different
default value of the flag argument (use URL
<>), I'll be glad to
fix it for the next printing, changing the previously quoted sentence

shelve supplies a function open that is polymorphic to
(except that the default value of argument flag is 'c' rather than 'n').

BTW, if you DO want to call 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 =, 'n')

since 'n' truncates an existing file, or creates a new one, as needed.

That is also shown in the code example for module shelve in the Nutshell
(the 'n' occurs just at the top of p. 285).


More information about the Python-list mailing list