best way to check if a file exists?

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Oct 31 20:55:29 EST 2006


georgeryoung at gmail.com writes:

> On Oct 31, 4:01 pm, John Salerno <johnj... at NOSPAMgmail.com> 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
post.

> You could be more "pythonic", and simply try to create the file,
> catching the exception if if fails.  This works on linux:
>
> try:
>    newfd = os.open('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 'os.open' *and* 'os.fdopen' will only ever
raise OSError if the file already exists, and not for any other OS
errors?

-- 
 \        "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