FileExists() in Python?

Alex Martelli aleaxit at yahoo.com
Sun May 13 13:37:00 EDT 2001


"Owen F. Ransen" <ransen_spam_me_not at nemo.it> wrote in message
news:3afeb5b7.1138522 at news.newsguy.com...
> What is the best style for writing a platform
> independent FileExists function? Using exceptions?

How do you want your FileExists to differ from the
existing os.path.exists function?

Using exceptions (try to use the file, catch the
exception if it doesn't exist) may well be a rather
preferable *alternative* -- it's more solid, as in
any modern platform other programs might be
running so there's no guarantee that the file's
existence state is the same between the moment
you check for it and the later moment you rely
on it (it can have been created or erased by some
other program during that timelag...).

Checking first is called the "Look before you leap"
idiom.  It's most natural to most people, but often
not best.  Trying to do whatever and catching the
exceptions is called the "It's easier to ask forgiveness
than permission" idiom (in honor of Rear-Admiral Grace
Murray-Hopper, arguably the most significant woman
in computing history so far, and well known for that
motto -- albeit she used it about dealing with some
kind of bureaucracy or hierarchy, since the language
she invented, Cobol, did not support exceptions:-).

Programming by "EAFTP" takes a slight mental shift
but it turns out to be a very good idiom in most cases
(key exceptions being somewhat-rare situations in
which you must strive to avoid _partial_ state-changes,
ensuring as far as feasible that some set of operations
takes place either completely or not at all -- in that
case, very careful and thorough preliminary checking
by "LBYL" may indeed be easier than trying to restore
a partly-changed state when working by "EAFTP"...).


Alex






More information about the Python-list mailing list