Oct 14, 2023 4 min read

How to Delete (Remove) Files and Directories in Python

Delete files and directories in Python with our step-by-step tutorial. A programming language known for its simplicity and readability.

Delete(Remove) Files and Directories in Python
Table of Contents

Introduction

Before we begin talking on how to delete files and directories in Python. Let’s briefly understand - What is Python?

Python is a high-level, interpreted, and general-purpose programming language known for its simplicity and readability. Created by Guido van Rossum and first released in 1991,it emphasizes code readability and usability, making it an excellent choice for beginners and experienced developers alike.

In Python, you can delete files and directories programmatically using various methods provided by the os and shutil modules. These modules offer functions that allow you to interact with the file system, providing flexibility when it comes to deleting files and directories.

In this tutorial, we will provide a brief introduction on how to delete files and directories in Python, explaining different approaches and methods that can be used.

Deleting Files

To delete a single file in Python, you can use os.remove(), os.unlink(), pathlib.Path.unlink().

The os module allows you to interact with the operating system from anywhere. Both Python 2 and Python 3 support the module.

To delete a single file with os.remove(), specify the file's path as an argument:

import os

file_path = '/tmp/file.txt'
os.remove(file_path)

The functions os.remove() and os.unlink() are semantically equivalent:

import os

file_path = '/tmp/file.txt'
os.unlink(file_path)

An error reading FileNotFoundError is raised if the requested file does not exist. Only files can be deleted using os.remove() and os.unlink(), not directories. They will return the IsADirectoryError error if the provided path corresponds to a directory.

A directory containing a file must have both write and execute permissions in order to delete it. Otherwise, you will receive a PermissionError error.

You can use exception handling to catch the exception and send the appropriate error message to prevent errors when deleting files:

import os

file_path = '/tmp/file.txt'

try:
    os.remove(file_path)
except OSError as e:
    print("Error: %s : %s" % (file_path, e.strerror))

Python 3.4 and above support the pathlib module. You can use pip to install this module in Python 2 if you want to use it. pathlib provides an object-oriented interface for working with file system paths across many operating systems.

To delete a file with the pathlib module, first create a Path object pointing to the file and then call the unlink() method on the object:

from pathlib import Path

file_path = Path('/tmp/file.txt')

try:
    file_path.unlink()
except OSError as e:
    print("Error: %s : %s" % (file_path, e.strerror))

You can also use pathlib.Path.unlink(), os.remove(), and os.unlink() delete a symlink.

Pattern matching

The glob module enables pattern-based matching across many files. For instance, you might use the following to delete every .txt file located in the /tmp directory:

import os
import glob

files = glob.glob('/tmp/*.txt')

for f in files:
    try:
        f.unlink()
    except OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

Use the "**" pattern and the recursive=True argument to the glob() function to recursively remove all .txt files in the /tmp directory and all subdirectories under it:

import os
import glob

files = glob.glob('/tmp/**/*.txt', recursive=True)

for f in files:
    try:
        os.remove(f)
    except OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

Two glob functions, glob() and rglob(), are available in the pathlib module to match files in a specified directory. glob() only matches files in top-level directories. rglob() recursively matches all files in the directory and all subdirectories. The example code below removes all .txt files from the /tmp directory:

from pathlib import Path

for f in Path('/tmp').glob('*.txt'):
    try:
        f.unlink()
    except OSError as e:
        print("Error: %s : %s" % (f, e.strerror))

Deleting Directories (Folders)

Use os.rmdir() and pathlib.Path.rmdir() to delete an empty directory, and shutil.rmtree() to delete a non-empty directory in Python.

To delete an empty directory in Python, use os.rmdir() and pathlib.Path.rmdir(). To delete a non-empty directory, use shutil.rmtree().

The following example demonstrates how to remove an empty directory:

import os

dir_path = '/tmp/img'

try:
    os.rmdir(dir_path)
except OSError as e:
    print("Error: %s : %s" % (dir_path, e.strerror))

Alternatively, you can use the pathlib module to delete directories:

from pathlib import Path

dir_path = Path('/tmp/img')

try:
    dir_path.rmdir()
except OSError as e:
    print("Error: %s : %s" % (dir_path, e.strerror))

Several high-level operations can be carried out on files and directories using the shutil module.

You can remove a specific directory and all of its contents using the shutil.rmtree() function:

import shutil

dir_path = '/tmp/img'

try:
    shutil.rmtree(dir_path)
except OSError as e:
    print("Error: %s : %s" % (dir_path, e.strerror))

The argument that passed to shutil.rmtree() cannot be used to create a symbolic link to a directory.

FAQs to Delete Files and Directories in Python

Can I delete multiple files at once in Python? 

Yes, you can delete multiple files at once by using a loop to iterate over the file paths and call os.remove() for each file.

How do I delete a directory in Python? 

To delete a directory in Python, you can use the shutil.rmtree() function, passing the directory path as the argument.

Can I delete a directory only if it is empty?

 No, the shutil.rmtree() function deletes the entire directory and its contents, regardless of whether it is empty or not. Make sure to exercise caution while using this function.

How do I delete a directory and its contents in Python? 

To delete a directory and its contents, you can use the shutil.rmtree() function to recursively remove all files and subdirectories within the directory.

Can I delete read-only files in Python? 

No, attempting to delete a read-only file will result in a PermissionError. You may need to change the file permissions before deleting it.

Can I delete files or directories from different drives using Python? 

Yes, you can delete files or directories from different drives by specifying the correct file paths using the appropriate drive letter or full path.

How can I delete files matching a specific pattern or wildcard using Python? 

You can use libraries such as glob or fnmatch to match files based on specific patterns or wildcards and delete them accordingly.

Conclusion

When deleting files or directories, it's essential to handle exceptions gracefully and verify the existence of files or directories before attempting deletion. Error handling helps ensure that your code functions correctly, even in cases where permissions or file existence may pose challenges.

We have covered os.remove(), os.unlink(), pathlib.Path.unlink() to delete a single file, os.rmdir() and pathlib.Path.rmdir() to delete an empty directory and shutil.rmtree() to recursively delete a directory and all of its contents.

If you have any suggestions or queries, kindly leave them in the comments section.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.