Computer Science Atlas
Code Review

Python 3 Examples: Remove Directory Recursively (Like rm -r)

February 11, 2021
 

Using shutil

On the Linux command line, if you want to remove (delete) a directory and all of its contents (including subdirectories), you can use the "recursive" (-r) option of the rm command. For example, to remove directory /tmp/mydir and all of its contents, you would run: rm -r /tmp/mydir.

Here is the Python 3 equivalent of that command:

Copy
import shutil

shutil.rmtree( '/tmp/mydir' )
1
2
3
import shutil

shutil.rmtree( '/tmp/mydir' )

pathlib Compatibility

If you're using pathlib on Python 3.4 and up, you can also use shutil.rmtree with pathlib.Paths as well. The pathlib library does not have its own recursive directory removal function (pathlib rmdir only removes empty directories), so this is the way to delete a directory and all of its contents with a pathlib.Path:

Copy
import pathlib
import shutil

mydir = pathlib.Path( '/tmp/mydir' )
shutil.rmtree( mydir )
1
2
3
4
5
import pathlib
import shutil

mydir = pathlib.Path( '/tmp/mydir' )
shutil.rmtree( mydir )

References