How to Remove a Non-Empty Folder in Python?

Rate this post

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 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:

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!