how do i check if a file exists with python?

David C. Ullrich ullrich at
Fri Dec 29 15:02:25 CET 2000

On Fri, 29 Dec 2000 16:54:56 +0200 (IST), Moshe Zadka
<moshez at> wrote:

>[Scott Hathaway, on how to find a file]
>> Thanks for both responses!
>Unfortunately, I think they did you more harm then good by telling you
>the answer: I doubt you need it. Now, it may be that I'm wrong, in which
>case just go ahead an use os.path.isfile, but if you're doing something
>def foo():
>	if os.path.isfile("foo"):
>		return open("foo")
>	else:
>		return None
>Or something to that effect, *don't*. It's evil, and will come back
>to bite you (unreadable existing files, files changing between isfile
>and open, etc.).
>Instead, simple do:
>def foo():
>	try:
>		return open("foo")
>	except IOError:
>		return None
>In other words, don't try to avoid exceptions -- know where you want
>to deal with them, and do so.

Hmm. Probably isfile should be removed from the language,
since it's considered harmful, eh?

It's certainly true the the second foo is better than the first,
in fact yes the first is evil. But there are other reasons a person 
might want to know whether a file exists (although probably
things like foo are the most likely explanation.)

I sometimes make cumulative backups of files containing
important stuff. I sort of need to determine that file.001,
file.002 and file.003 already exist and file.004 does not
before deciding what to name the current backup file.

(When I tell people they're asking the wrong question I
get in trouble for it...)

>Moshe Zadka <sig at>
>This is a signature anti-virus. 
>Please stop the spread of signature viruses!

More information about the Python-list mailing list