best way to check if a file exists?

Ben Finney bignose+hates-spam at
Wed Nov 1 02:55:29 CET 2006

georgeryoung at writes:

> On Oct 31, 4:01 pm, John Salerno <johnj... at> wrote:
> > What is the best way to check if a file already exists in the
> > current directory? I saw os.path.isfile(), but I'm not sure if
> > that does more than what I need.

I see that 'os.path.exists' has already been pointed out in a later

> You could be more "pythonic", and simply try to create the file,
> catching the exception if if fails.  This works on linux:
> try:
>    newfd ='foobar', os.O_EXCL | os.O_CREAT)
>    new_file = os.fdopen(newdf)
> except OSError, x:
>    if x[1] == 'File exists':
>       handle_file_exists()

Are you sure that both of '' *and* 'os.fdopen' will only ever
raise OSError if the file already exists, and not for any other OS

 \        "We have to go forth and crush every world view that doesn't |
  `\             believe in tolerance and free speech."  -- David Brin |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list