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:
1 2 3 | import shutil shutil.rmtree( '/tmp/mydir' ) |
pathlib
CompatibilityIf you're using pathlib
on Python 3.4 and up, you can also use shutil.rmtree
with pathlib.Path
s 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
:
1 2 3 4 5 | import pathlib import shutil mydir = pathlib.Path( '/tmp/mydir' ) shutil.rmtree( mydir ) |