delete file

David Bolen db3l at
Wed Jul 16 00:40:06 CEST 2003

Gerhard Häring <gh at> writes:

> if not os.path.exists("foo"):
>      os.remove("foo")

Wouldn't you want this to be a positive check (e.g., without "not")?

> or just catch the error, with something like:
> try:
>      os.remove("foo")
> except OSError, detail:
>      if detail.errno != 2:
>          raise

For the OP, the second option should in general be preferred, since
even in the first case, the file might disappear between when the
exists() call is made and when the remove() call is made.

Or put another way, even if you do want to use os.path.exists() to
conditionalize the execution of some code, you'll need to realize that
the check won't guarantee that the file remains present for any
specific length of time following the check.  So for maximum
robustness you'd need to protect the os.remove() call anyway, and
might as well dispense with the initial check and just attempt the

-- David

More information about the Python-list mailing list