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

Roy Smith roy at panix.com
Sat Dec 11 12:04:01 EST 2010


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".  I could 
do:

if os.access("file", os.F_OK):
   os.unlink("file")

but that's annoying too.  What would people think about a patch to 
os.unlink() to add an optional second parameter which says to ignore 
attempts to remove non-existent files (just like "rm -f")?  Then you 
could do:

os.unlink("file", ignore=True)



More information about the Python-list mailing list