Delete File or Folder in Python?

How to delete files or folders in Python? There are several ways to delete a file or folder, each with its own advantages and use cases. To delete a file or folder, you can use the python os module, shutil module, and many others. In this article, we’ll take a look at the different methods for deleting files and folders in Python.

We will also cover some advanced techniques for deleting files in bulk, deleting files based on a pattern or criteria, and removing folders with subfolders.

1. Quick Examples to Delete Files or Folder In Python

The below examples gives a high-level overview of the different methods and scenarios covered in this article. We will discuss each method in much more detail, explaining their advantages and use cases.


# Set the directory path
directory_path = 'Replace Directory Path Here'

# Deleting a File
# Removing a file with os.remove()
import os
os.remove(directory_path + 'myfile.txt')

# Removing a file with pathlib.Path.unlink()
import pathlib
pathlib.Path(directory_path + 'myfile.txt').unlink()

# Deleting Files in Bulk
# Removing all files from a directory
import glob
files = glob.glob(directory_path + '*')
for file in files:
    os.remove(file)

# Deleting a Folder
# Removing an empty folder with os.rmdir()
os.rmdir(directory_path + 'empty_directory')

# Removing a non-empty folder with shutil.rmtree()
import shutil
shutil.rmtree(directory_path + 'folder')

2. Deleting File in Python

There are multiple ways to delete a file in Python. These include removing a file with os.remove(), removing a file with os.unlink(), and removing a file with pathlib.Path.unlink(). We will go through each method in detail, explaining how to use them and in what scenarios they are most useful.

2.1 Delete Files using os.remove()

os.remove() is a built-in function in the Python os module that can be used to delete a file. It takes a single argument, which is the path to the file you want to delete.


# Import os module
import os

# Delete file
file_path = "file.text"
os.remove(file_path)

os.remove() will only work if the file exists and the user has the necessary permissions to delete it. If the file doesn’t exist, os.remove() will raise a FileNotFoundError. If the user doesn’t have the necessary permissions to delete the file, os.remove() will raise a PermissionError.

It is better to use Error Handling when working with os.remove() for deleting files in python.


# Import os module
import os

file_path = "directory_path/file.txt"

# Exception handling
try:
    os.remove(file_path)
    print("successfully deleted.")
except FileNotFoundError:
    print("File not found.")
except PermissionError:
    print("Do not have permission to delete file")

It is similar to the os.remove() function, but os.unlink() is only available on Unix-based systems, while os.remove() works on both Unix-based and Windows systems.

If the file is successfully deleted, os.unlink() does not return a value. If the file cannot be deleted, os.unlink() raises an exception.


# Import os module
import os

# Delete file using os.unlink()
file_path = "/path/to/file"
os.unlink(file_path)

To delete a file using pathlib.Path, we can use the unlink() method. The unlink() method is similar to os.unlink(), but it provides a more object-oriented interface.


# Import pathlib
from pathlib import Path

# Specify the file path
file_path = Path("file.txt")

# Check if the file exists before deleting it
if file_path.exists():
    # Delete the file
    file_path.unlink()
    print("File deleted successfully.")
else:
    print("File not found.")

The main difference between the two methods is that pathlib.Path.unlink() is part of the pathlib module, which provides a more object-oriented approach to working with file paths than the os module.

3. Deleting a Folder in Python

Deleting a folder in Python is similar to deleting a file but requires additional consideration since folders can contain multiple files and subfolders. There are different ways to delete a folder in Python, depending on whether it is empty or contains files and subfolders.

In this section, we will explore how to delete a folder using two different methods: os.rmdir() for deleting an empty folder and shutil.rmtree() for deleting a non-empty folder.

3.1 os.rmdir() – Deleting an Empty Folder

The os.rmdir() method can be used to delete an empty folder in Python. It takes the directory path as a parameter and removes it if the directory is empty. If the directory contains files or subdirectories, the method will raise an OSError.


import os

# Delete folder
try:
    # Remove empty directory
    os.rmdir(directory_path)
    print("Directory removed successfully")
except OSError as error:
    print(error)

3.2 shutil.rmtree() – Deleting Non-empty Folder

The shutil module provides the rmtree() function to remove a directory and its contents, including all subdirectories and files. This function is used to delete non-empty directories.


import shutil

# Delete folder using shutil
try:
    shutil.rmtree(folder_path)
    print(f"The folder at {folder_path} has been successfully deleted!")
except OSError as e:
    print(f"Error: {folder_path} - {e.strerror}.")

4. Removing all Files From a Directory

Sometimes we may need to delete all the files in a directory. There are several ways to achieve this in Python. We can use the os module to accomplish this task. A simpler way to achieve this is to use the glob module, which allows us to search for files using patterns.


# Imports
import glob
import os

# Get a list of all the files in the directory
file_list = glob.glob(directory_path + '*')

# Loop through the list of files and delete each file
for file_path in file_list:
    try:
        os.remove(file_path)
        print(f"{file_path} deleted successfully.")
    except OSError as e:
        print(f"Error: {file_path} : {e.strerror}")

5. Removing Files Matching a Pattern

We can use pattern matching to delete all files or folders in which we are interested and leave the others. Below are some use cases that can help you understand the whole concept.

5.1 Deleting Files with Specific Extension

This involves deleting all files in a directory with a specific extension, such as .txt or .csv.


# This code will delete only text files
extension = ".txt"

for file_name in os.listdir(folder_path):
    if file_name.endswith(extension):
        os.remove(os.path.join(folder_path, file_name))

5.2 Delete Files – Starts with a Specific String

This involves deleting all files in a directory whose names start with a specific string, such as “image_” or “data_”.


# This code delete all files that start with Python
start_string = "Python"

for file_name in os.listdir(folder_path):
    if file_name.startswith(start_string):
        os.remove(os.path.join(folder_path, file_name))

5.3 Delete Files – Contains Specific Letters

This involves deleting all files in a directory whose names contain specific letters, such as “log” or “report”.


letters = "abc"

for file_name in os.listdir(folder_path):
    if letters in file_name:
        os.remove(os.path.join(folder_path, file_name))

6. Summary and Conclusion

We have covered various ways to delete files and folders in Python. This includes how to remove files using os.remove(), os.unlink(), and pathlib.Path.unlink(). And how to remove folders using os.rmdir() and shutil.rmtree(). If you have any questions or feedback, feel free to leave a comment below.

Happy coding!

AlixaProDev

I am an astute software engineer with extensive 3+ years of experience in developing full-stack web applications. My skillets include building backend services for different databases. Mainly I work with Python, Flask, Django, and FastAPIs. Being Python Specialist, I have worked with Numpy, Pandas, and other Python Libraries to build tools that make ETL normalization easier.

Leave a Reply