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

Christian Heimes lists at cheimes.de
Sat Dec 11 12:25:14 EST 2010


Am 11.12.2010 18:04, schrieb Roy Smith:
> 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:

-1

os.unlink is a small wrapper around the unlink(2) function.

You want to ignore the ENOENT error number and re-raise the exception
for other errors:

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

You may be interested in EISDIR, too. unlink() doesn't remove directories.

Christian




More information about the Python-list mailing list