Problem Formulation:
- Given a
path
to a folder as a Python string. The folder is non-empty. - How to remove the whole folder in your Python script?
Example: Say, you have the path='path/to/folder'
in your Python script and it contains some files and subfolders:
path
--to
----folder
------file1.dat
------file2.dat
------subfolder1
--------file3.dat
------subfolder2
--------file4.dat
You want to remove all the bold content in the previous example folder structure.
Method 1: Remove Files At Once with shutil.rmtree()
The module shutil
provides a function rmtree()
that removes all folders and files recursively from a given path.
import shutil # String path of folder to be removed: path = 'path/to/folder' # Remove the folder recursively: shutil.rmtree(path)
The shutil.rmtree()
function deletes the entire directory tree at the provided path pointing to a directory (not a file or a symbolic link of a directory).
Note that read-only files cannot be removed from a folder using this utility because they are, well, read only. That’s why it’ll throw an error when you try to remove read-only files. If you want to remove the remaining folder contents regardless, you need to set the optional argument ignore_errors
.
shutil.rmtree(path, ignore_errors=True)
However, the read-only files won’t be removed in any case!
Method 2: Remove Files Individually with os.walk()
A more fine-grained approach is provided by the os.walk()
function:
import os # String path of folder to be removed: path = 'path/to/folder' # Remove the folder by walking through the files (from the bottom up): for root, dirs, files in os.walk(path, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name))
ATTENTION: Before using this code make sure it’s tailored to your specific problem as it can potentially remove all files in your operating system if you specify your top-level path as ‘/’ or any other root path in your specific operating system.
- The
os.walk(path, topdown=False)
method provides an iterator over all files at the givenpath
. Thetopdown=False
argument ensures that you move from the bottom up, i.e., you first remove all the contents of a folder before deleting the folder itself. - The
os.remove(os.path.join(root, name))
method removes the file at the locationroot + name
wherename
is the file suffix (e.g.,'file.dat'
) androot
is the path to this file (e.g.,'/path/to/file/'
). - The
os.rmdir(os.path.join(root, name))
method removes the folder at the locationroot + name
wherename
is the folder suffix (e.g.,'file.dat'
) androot
is the path to this file (e.g.,'/path/to/file/'
).
Method 3: Walking over Files and Folders Using pathlib
import pathlib # String path of folder to be removed: path = 'path/to/folder' # Remove the folder del_folder(path): for sub in path.iterdir(): if sub.is_dir(): # Delete folder if it is a folder del_folder(sub) else : # Delete file if it is a file: sub.unlink() # This removes the top-level folder: path.rmdir() del_folder(pathlib.Path(path))
Resources:
- https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty
- https://stackoverflow.com/questions/1557351/python-delete-non-empty-dir
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.