How to delete files in python

Overview

In this tutorial, we are going to learn how to delete files in Python. The Python programming language comes with the os and shutil modules that we are going to use for our purpose.

Here are the things we will cover:

  • Deleting a file in Python
  • Delete all files in directory
  • Deleting files using wildcard
  • How to delete all files in a directory with extension

Deleting a file in Python

We are going to use the os.remove function to delete a single file. This function does not delete directories. We will cover deleting directories later.

import os

file_to_delete = "/home/simplecodegeeks/file.txt"
try:
    os.remove(file_to_delete)
    print ('File deleted')
except FileNotFoundError:
    print ('File not file:', file_to_delete)

Deleting all files in a directory

In Python, you can use os.rmdir() and pathlib.Path.rmdir() to delete an empty directory and shutil.rmtree() to delete a non-empty directory.

import os

dir_path = '/home/simplecodegeeks/img'

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

The shutil module allows you to perform a number of high-level operations on files and directories.

With the shutil.rmtree() function you can delete a given directory including its content:

import shutil

dir_path = '/home/simplecodegeeks/img'

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

Conclusion

Python provides several modules for working with files.

We’ve shown you how to delete files in Python using 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 it’s contents.

If you have any questions or feedback, feel free to leave a comment.

Share this article

About Michael Mulikita

Founder of Simplecodegeeks.com, I love programming and open source technologies. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

View all posts by Michael Mulikita →

Leave a Reply