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

R

Roy Smith

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)
 
N

Nobody

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.
 
R

Roy Smith

Christian Heimes said:
Am 11.12.2010 18:04, schrieb Roy Smith:

-1

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

OK, fair enough. Perhaps a better place would be in a higher level
module like shutil.

It was suggested I look at shutil.rmtree(), but that only works of path
is a directory. Also, the meaning of the ignore_errors flag is not
quite what I'm looking for. I don't want to ignore errors, I just want
"if it doesn't exist, this is a no-op". In short, exactly what "rm -r"
does in the unix shell.

So, maybe a new function is shutils?

shutils.rm(path, force=False)
Delete the file at path. If force is True, this is a no-op if path does
not exist. Raises OSError if the operation fails.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top