简体   繁体   English

像“rm -f”中一样强制删除文件,或强行取消链接文件路径

[英]Remove a file forcefuly as in “rm -f” or unlink a filepath from directory forcefully

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. 我相信os.remove(文件)相当于linux中的“rm文件”。

I would like to know the equivalent function for "rm -f file". 我想知道“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; 但是当我使用“rm -f”到同一个文件时; it is getting deleted. 它被删除了。

I think it is better to ask a question, even though it sounds stupid to yourselves 我觉得问一个问题比较好,即使这听起来很愚蠢

The --force option to rm means, to ignore non existing files and never prompt , according to my man page. 根据我的手册页, rm--force选项意味着忽略不存在的文件从不提示

The never prompt part is easy, your python remove does not prompt, right? 从不提示部分很容易,你的python删除不提示,对吧?

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...). 或者你可以捕获OSError,并验证它是否被抛出,因为该文件不存在(OSError:[Errno 2]没有这样的文件或目录......)。 One other reason for the OSError is, that the file you want to remove is not a file but a directory. OSError的另一个原因是,要删除的文件不是文件而是目录。

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. force选项执行mo权限魔法(至少在我的linux上),请记住,删除文件是对目录的写操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM