aleax at mac.com
Mon Apr 9 04:14:12 CEST 2007
7stud <bbxx789_05ss at yahoo.com> wrote:
> On Apr 4, 10:22 pm, mik3l3... at gmail.com 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 anydbm.open .
On p. 286, you find the whole page explaining anydbm.open (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, shelve.open is not
_entirely_ polymorphic to anydbm.open, 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 anydbm.open
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
But if you open an errata for the missing explanation for the different
default value of the flag argument (use URL
<http://www.oreilly.com/catalog/pythonian2/errata/>), 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 anydbm.open
(except that the default value of argument flag is 'c' rather than 'n').
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.
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