Easiest way to rm -rf in Python

Python

Python Problem Overview


What is the easiest way to do the equivalent of rm -rf in Python?

Python Solutions


Solution 1 - Python

import shutil
shutil.rmtree("dir-you-want-to-remove")

Solution 2 - Python

While useful, rmtree isn't equivalent: it errors out if you try to remove a single file, which rm -f does not (see example below).

To get around this, you'll need to check whether your path is a file or a directory, and act accordingly. Something like this should do the trick:

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)

Note: this function will not handle character or block devices (that would require using the stat module).

Example in difference of between rm -f and Python's 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'

Edit: handle symlinks; note limitations as per @pevik's comment

Solution 3 - Python

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)

Slightly improved Gabriel Grant's version. This works also on symlinks to directories. Note: function does not handle Un*x character and block devices (it would require to use stat module).

Solution 4 - Python

def delite(filepath):

    import os, stat, sys
    def intertwin(_list):
        list1 = []
        for i in _list:
            list1 += i
        return list1
    allpath = os.walk(filepath)
    walk = []
    dirs = []
    path = []
    allfiles = []
    for i in allpath:
        walk.append(i)
    for i in walk:
        dirs.append(i[0])
    for _dir in dirs:
        os.chdir(_dir)
        files = os.listdir(_dir)
        files1 = []
        for i in files:
            files1.append(_dir + '\\' + i)
        files = files1[:]
        allfiles.append(files)
    allfiles = intertwin(allfiles)
    for i in allfiles:
        os.chmod(i, stat.S_IRWXU)
    allfiles.reverse()
    os.chdir(sys.path[0])
    for i in allfiles:
        try:
            os.remove(i)
        except:
            try:
                os.rmdir(i)
            except:
                pass
    os.chmod(filepath, stat.S_IRWXU)
    try:
        os.remove(filepath)
    except:
        os.rmdir(filepath)
        allfiles.reverse()
        os.chdir(sys.path[0])
        for i in allfiles:
            try:
                os.remove(i)
            except:
                try:
                    os.rmdir(i)
                except:
                    pass
        os.chmod(filepath, stat.S_IRWXU)
        try:
            os.remove(filepath)
        except:
            os.rmdir(filepath)

Solution 5 - Python

A workaround for Windows where it blocks deletion of file is to truncate the file:

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

source: https://stackoverflow.com/a/2769090/6345724

Solution 6 - Python

shutil.rmtree() is right answer, but just look at another useful function - os.walk()

Solution 7 - Python

Just do this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJosh GibsonView Question on Stackoverflow
Solution 1 - PythonJosh GibsonView Answer on Stackoverflow
Solution 2 - PythonGabriel GrantView Answer on Stackoverflow
Solution 3 - PythonpevikView Answer on Stackoverflow
Solution 4 - PythonPogramistView Answer on Stackoverflow
Solution 5 - PythonDanView Answer on Stackoverflow
Solution 6 - PythonmaxpView Answer on Stackoverflow
Solution 7 - PythonOluwatobi OlabiyiView Answer on Stackoverflow