在Python中使用rm -rf的最简单方法

Jos*_*son 61 python

rm -rf在Python中执行相同操作的最简单方法是什么?

Jos*_*son 71

import shutil
shutil.rmtree("dir-you-want-to-remove")
Run Code Online (Sandbox Code Playgroud)

  • 虽然有用,但rmtree并不等效:如果您尝试删除单个文件,则会出错. (21认同)

Gab*_*ant 35

虽然有用,但rmtree并不等效:如果您尝试删除单个文件,则会出错rm -f(请参阅下面的示例).

要解决这个问题,您需要检查您的路径是文件还是目录,并采取相应措施.像这样的东西应该做的伎俩:

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)
Run Code Online (Sandbox Code Playgroud)

注意:此函数不会处理字符或块设备(需要使用该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'
Run Code Online (Sandbox Code Playgroud)

编辑:处理符号链接; 请注意@ pevik评论的限制

  • 这个版本对符号链接到目录不起作用,因为python在`os.path.isdir(symlink_to_directory)上返回`True` (2认同)

pev*_*vik 7

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)
Run Code Online (Sandbox Code Playgroud)

稍微改进了加布里埃尔·格兰特的版本。这也适用于目录的符号链接。

注意:函数不处理Un*x 字符和块设备(需要使用stat模块)。