Making os.unlink() act like "rm -f"

Nobody nobody at nowhere.com
Sat Dec 11 12:25:20 EST 2010


On Sat, 11 Dec 2010 12:04:01 -0500, Roy Smith wrote:

> I just wrote an annoying little piece of code:
> 
> try:
>     os.unlink("file")
> except OSError:
>    pass
> 
> The point being I want to make sure the file is gone, but am not sure if
> it exists currently.  Essentially, I want to do what "rm -f" does in the
> unix shell.
> 
> In fact, what I did doesn't even do that.  By catching OSError, I catch
> "No such file or directory" (which is what I want), but I also catch lots
> of things I want to know about, like "Permission denied".

import errno
try:
    os.unlink("file")
except OSError as e:
    if e.errno != errno.ENOENT:
        raise

> I could do:
> 
> if os.access("file", os.F_OK):
>    os.unlink("file")
> 
> but that's annoying too.

It also has a race condition. EAFP is the right approach here.




More information about the Python-list mailing list