Remove a file forcefuly as in "rm -f" or unlink a filepath from directory forcefully

aslamplr picture aslamplr · Mar 4, 2012 · Viewed 8.8k times · Source

I have my code as follows -

#!/usr/bin/env python
import time, glob, os, sys
from datetime import date, timedelta

try:
    dpath = sys.argv[1]+"/"
except:
    print "usage: " + sys.argv[0] +" <dir_path_to_purge_files>"
    sys.exit(1)
print dpath
day_minus_mtime = time.mktime(date.today().timetuple())
g = glob.glob(dpath+"*")
for f in g:
        try:
                if day_minus_mtime > os.path.getmtime(f):
                        os.remove(f)
                        print "Removed: "+f
        except OSError, e:
                print "Not able to Remove: "+f , e

I believe that os.remove(file) is equivalent to "rm file" in linux.

I would like to know the equivalent function for "rm -f file". Forcefully remove a file or Forcefully unlink the file path from directory.

Also the above code is trying to purge files older than today. I have a situation where the files are not deleted as it is "write-protected" due to the ownership. But when I use "rm -f" to the same file; it is getting deleted.

I think it is better to ask a question, even though it sounds stupid to yourselves

Answer

J&#246;rg Beyer picture Jörg Beyer · Mar 4, 2012

The --force option to rm means, to ignore non existing files and never prompt, according to my man page.

The never prompt part is easy, your python remove does not prompt, right?

The ignore non existing files is also easy: you could either check, if the file exists, right before you remove it. You have a small race condition, because the file might disappear between the existence check and the remove. Or you could catch the OSError, and verify that it is thrown because the file does not exist (OSError: [Errno 2] No such file or directory...). One other reason for the OSError is, that the file you want to remove is not a file but a directory.

The force option does mo permission magic (at least on my linux), just keep in mind, that removing a file is a write operation on the directory.