Forcibly delete the file, as in "rm -f", or cancel the file path from the directory

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 the "rm file" in Linux.

I would like to know the equivalent function for "rm -f file". Strongly delete the file or force cancel the path to the file from the directory.

In addition, the above code tries to clear files older than today. I have a situation where files are not deleted, as they are "write protected" due to ownership. But when I use "rm -f" in the same file; he is removed.

I think it's better to ask a question, although that sounds silly to myself.

+4
source share
1 answer

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

The part is never needed, your python remove will not tell you, right?

Ignoring non-existent files is also easy: you can either check if the file exists before deleting it. You have a slight race condition because the file may disappear between the existence check and the deletion. Or you can catch OSError and make sure it is selected because the file does not exist (OSError: [Errno 2] There is no such file or directory ...). Another reason for OSError is that the file you want to delete is not a file, but a directory.

The force parameter does permission magic (at least on my Linux), just keep in mind that deleting a file is a write operation in a directory.

+4
source

Source: https://habr.com/ru/post/1399657/


All Articles