How to Remove a Non-Empty Folder in Python? – Be on the Right Side of Change (2024)

by Chris

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 given path. The topdown=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 location root + name where name is the file suffix (e.g., 'file.dat') and root 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 location root + name where name is the folder suffix (e.g., 'file.dat') and root 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 folderdel_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:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. 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?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming 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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

How to Remove a Non-Empty Folder in Python? – Be on the Right Side of Change (1)

Chris

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 that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a 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.

How to Remove a Non-Empty Folder in Python? – Be on the Right Side of Change (2024)
Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 5929

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.