[Tutor] try and file existence

boB Stepp robertvstepp at gmail.com
Sat Aug 15 21:24:21 CEST 2015

On Fri, Aug 14, 2015 at 10:39 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, Aug 14, 2015 at 06:28:09PM -0700, Clayton Kirkwood wrote:

> > what is the best way to find out if a file exists?
> Try to open it and see what happens. If the open() succeeds, then the
> file exists and can be read. If it fails, then either the file doesn't
> exist, or it can't be read. Inspect the error to find out which.
> There is also os.path.exists(filename), but you should avoid using that
> if possible. The problem is this:
> if os.path.exists(filename):
>     # file exists *right now*
>     # but a millisecond later, some other program deletes it...
>     # and now it doesn't exist any more
>     with open(filename) as f:  # gives an error
>         ...

I understand your points, but wonder then what is the intended use for
os.path.exists()?  That is, in what types of circumstances would it be
both appropriate and safe to use?


More information about the Tutor mailing list