在Python中实现rm-rf的最简单方法

在Python中实现rm-rf的最简单方法,python,Python,在Python中,做rm-rf等价物的最简单方法是什么?myfile $ls 我的文件 $rm-rf myfile $ls $echo“stuff”>myfile $ls 我的文件 $python Python 2.7.1+(r271:868321911年4月11日,18:13:53) [GCC 4.5.2]关于linux2 有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。 >>>进口舒蒂尔 >>>rmtree('myfile') 回溯(最近一次呼叫最后一次): 文件“”,第1行

在Python中,做
rm-rf
等价物的最简单方法是什么?

虽然有用,但rmtree并不等价:如果您试图删除单个文件,它就会出错,而
rm-f
则不会(参见下面的示例)

import shutil
shutil.rmtree("dir-you-want-to-remove")
要解决这个问题,您需要检查路径是文件还是目录,并采取相应的措施。像这样的事情应该可以做到:

import os
import shutil

def rm_r(path):
    if os.path.isdir(path) and not os.path.islink(path):
        shutil.rmtree(path)
    elif os.path.exists(path):
        os.remove(path)
注意:此功能不会处理字符或块设备(需要使用
stat
模块)

示例说明
rm-f
和Python的
shutils.rmtree

$ mkdir rmtest
$ cd rmtest/
$ echo "stuff" > myfile
$ ls
myfile
$ rm -rf myfile 
$ ls
$ echo "stuff" > myfile
$ ls
myfile
$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil
>>> shutil.rmtree('myfile')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/shutil.py", line 236, in rmtree
    onerror(os.listdir, path, sys.exc_info())
  File "/usr/lib/python2.7/shutil.py", line 234, in rmtree
    names = os.listdir(path)
OSError: [Errno 20] Not a directory: 'myfile'
$mkdir rmtest
$cd rmtest/
$echo“stuff”>myfile
$ls
我的文件
$rm-rf myfile
$ls
$echo“stuff”>myfile
$ls
我的文件
$python
Python 2.7.1+(r271:868321911年4月11日,18:13:53)
[GCC 4.5.2]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>进口舒蒂尔
>>>rmtree('myfile')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
rmtree中的文件“/usr/lib/python2.7/shutil.py”,第236行
onerror(os.listdir,path,sys.exc_info())
rmtree中的文件“/usr/lib/python2.7/shutil.py”,第234行
name=os.listdir(路径)
OSError:[Errno 20]不是目录:“myfile”
编辑:处理符号链接;根据@pevik的评论注意限制

import os
import shutil

def rm_r(path):
    if not os.path.exists(path):
        return
    if os.path.isfile(path) or os.path.islink(path):
        os.unlink(path)
    else:
        shutil.rmtree(path)
稍微改进了加布里埃尔·格兰特的版本。这也适用于指向目录的符号链接。 注意:函数不处理Un*x字符和块设备(需要使用模块)。

只需执行以下操作:

import os
dirname = "path_to_directory_to_remove"
os.system("rm -rf %s" % dirname)

Windows阻止删除文件的一个解决方法是截断文件:

outputFile = open(r"filename.txt","w") 
outputFile.truncate()
outputFile.close()
outputFile = open(r"filename.txt","a+") 

来源:

尽管rmtree很有用,但它并不等效:如果您尝试删除单个文件,它会出错。有关更通用的“删除非空目录”问题,请参阅:
rm-rf不存在的文件夹
工作正常(它不起任何作用),但是您的脚本将失败此版本无法在指向目录的符号链接上运行,因为python在
os.path.isdir(指向目录的符号链接)
上返回
True
,@pevik--修复了此问题。谢谢这不适用于权限不允许的目录,但您是root用户。在shell提示下,除非使用-f标志,否则将提示“override rw------for File.txt”。在python中,当上面的操作失败时,它会在提示下无声地工作。
os.remove
可以很好地删除设备;我刚试过。我不理解关于代码不能在设备文件上工作之类的评论。POSIX系统调用
unlink
不区分文件和设备。Downvote是因为它不是真正的python等价物。rm-rf只在*nix平台上工作,不是python代码。它也很危险,因为它没有转义dirname.danger和依赖于平台,但在需要“-f”的情况下工作。除此之外,上述解决方案均不适用于“-f”要求的情况。如果可能重复,即使属性为“只读”,也会删除包含文件或文件的文件夹,请:删除包含文件的文件夹或文件,即使属性为“只读”它是translater,我不太懂英语)您可能可以通过将
取消链接
放入备用案例来处理设备;如果检测到目录,请执行rmtree。也就是说,我们不必专门测试设备节点类型。
outputFile = open(r"filename.txt","w") 
outputFile.truncate()
outputFile.close()
outputFile = open(r"filename.txt","a+")