Problem Formulation: How to Remove a Directory in Python?
rm command in Linux removes a specific directory. You can also add the options
-rremove the directory recursively
-fignore nonexistent files and arguments and don’t prompt the user to ask for confirmation
So, if you run
rm -rf my_directory, it’ll forcefully remove
my_directory and all its child directories.
$ rm -rf my_directory
What is the best way to do the equivalent of
rm -rf in Python?
Method 1: shutil.rmtree()
The most Pythonic way to
rm -rf is to use the function
shutil.rmtree() defined in the
shutil package. It takes one argument, the folder to be removed, and removes the folder recursively.
import shutil shutil.rmtree('my_directory')
rmtree isn’t semantically identical to
rm -rf because it raises an error if you try to remove a single file.
If you generally want to suppress error messages, you can use the following command instead:
Method 2: os.unlink() and shutil.rmtree()
The following method resolves this problem of Python raising an error if you try to remove a single file.
import os, shutil def remove(path): if os.path.exists(path): if os.path.isfile(path) or os.path.islink(path): os.unlink(path) else: shutil.rmtree(path) remove('my_directory')
As pointed out here, this method works on symbolic links to directories in the directory to be removed.
Method 3: os.walk()
You can also remove a directory with all its content by using the
os.walk() method that goes over all files and folders in a given directory.
# CAUTION: top == '/' could delete all files on your disk! import os my_dir = '/my_directory' for root, dirs, files in os.walk(my_dir, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name))
Method 4: Remove Read Only Files in Windows
You can also remove a directory in Windows if files are in a read only mode by using the following code from the Python docs:
import os, stat, shutil def remove_readonly(func, path): os.chmod(path, stat.S_IWRITE) func(path) directory = 'my_dir' shutil.rmtree(directory, onerror=remove_readonly)
This example shows how to remove a directory tree named
'my_dir' on Windows where some of the files are read-only. The function is used as a callback to clear the readonly bit and reattempt the removal process. If there’s still an error, it’ll be propagated up to the main program.
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.