how do i check if a file exists with python?

Alex Martelli aleaxit at yahoo.com
Fri Dec 29 03:30:38 EST 2000


"Daniel Klein" <DanielK at aracnet.com> wrote in message
news:phU26.31$KD3.4767 at typhoon.aracnet.com...
> How about something like
>
> def fileExists(f):
>     try:
>         file = open(f)
>     except IOError:
>         exists = 0
>     else:
>         exists = 1
>     return exists
>
> Although this is not as elegant as the person who submitted the 'glob'
> solution.

This is one way to answer "did the file named by string f exist *IN A
FORM THAT COULD BE OPENED FOR READING BY THIS PROCESS* _at the time the
question was posed_", which is rather different from "does the file so
named exist at all right now".  Note that os.access with os.R_OK is
answering a subtly *different* question on systems where setgid/setuid
is a possibility (this often trips people up, but it's more of an issue
for non-scripting languages, since setuid scripts aren't popular, and
rightly so:-).

When somebody asks how to determine whether a file exists, it IS quite
likely that what they mean is something different, such as, whether it
could be read.  os.access with os.F_OK, or os.path.exists, or
os.path.isfile (maybe in conjunction with 'not os.path.islink', but
that depends on what position one takes on 'existence' of symbolic
links...), all answer existence-questions of some form or other.

It's unlikely, although of course possible, that 'actual existence'
is exactly what one needs to determine, and ALL one needs (and, in
general, if this IS indeed the question, it is not answerable: a file
COULD exist, but in a way that remains totally hidden from the current
process).  try/except *right in the code that DOES something with the
file* (typically opening it, if possible) is far more likely to be the
right approach -- it's just about the only way to address the issue
of 'right now' as opposed to 'back when I asked', although not totally
(on some systems, under certain situation, a file COULD be deleted
"from under you" even if you have it open... but, it's less likely to
happen than if you _didn't_ keep it open after asking:-).


Alex






More information about the Python-list mailing list