Kodeclik Blog


How to delete files in Python

Sometimes you might want to programmatically work with files from inside your Python program. For instance, you might want to create files, read and write to them, and even delete them! In this blogpost we will see how to delete files in Python.

Method 1: Use the os module

The most common way to delete files in Python is to use the os module. Within this module, we use the os.remove() function. os.remove() takes the file path as an argument and deletes the specified file. Here's an example of how to use it:
This script first imports the os module, and then sets the fp variable to the path of the file that needs to be deleted. The script then checks if the file exists at the specified path using os.path.exists(). If the file exists, it is deleted using os.remove(). If the file does not exist, a message is printed to indicate so.
The above code works to delete a specific file. Make sure to not delete the file containing your program!
To delete a folder (or a directory), you can use the os.rmdir() method. This works only if the folder has already been emptied out of files and other content (like subdirectories).

Method 2: Use the shutil module

shutil stands for "shell utilities" and provides a set of high-level operations on files and collections of files. It offers functions for tasks such as file copying, moving, and removal, as well as archiving. The shutil module is designed to automate and simplify the process of working with files and directories, making it a valuable tool for various file manipulation tasks.
To delete a file in Python using the shutil module, you can use the shutil.rmtree() function. This function is in general used to delete an entire directory tree, including all files and subdirectories inside it.
Here's an example of how to use shutil.rmtree() to delete a file:
So when should you use each method? It’s important to note that shutil.rmtree() is used to delete directories and all their contents, so it should be used with caution to avoid accidental data loss. If you only need to delete a single file, the os.remove() function is the appropriate choice for you.

Handling exceptions while deleting files

When deleting files programmatically in Python, it's important to handle exceptions that may occur during the deletion process. This is essential for gracefully managing potential errors, such as the file being in use by another process or insufficient permissions. The common approach to handle exceptions when deleting files is to use a try/except block. Here's an example of how to handle exceptions when deleting a file using the shutil module:
In this example, the shutil.rmtree() function is used to delete the file, and any exceptions that occur during the deletion process are caught and handled within the except block. This ensures that the program can respond appropriately to any errors that may arise during the file deletion.

When would we need to delete files programmatically?

Now that we know how to delete files in Python, when would we need to do it?
You may need to delete files programmatically from inside your program for various reasons, such as managing disk space, removing temporary files, or updating existing files. For example, let us assume you are writing a program that analyzes the weather across the United States and saves results into separate files, one for each city. As you analyze cities you might create several intermediate or temporary files which will need to be deleted to make space for new files. In such cases, the methods you learnt here are going to be very useful.
Here is an example program illustrating these ideas:
This program uses a for loop to create files with names "city.txt", "city2.txt", and so on. For now we are assuming that we have 5 cities, which is why the range parameter goes from 1 to 6 (recall that 6 is non-inclusive). For each iteration, the program prints a message saying "File created", does something with it (this part is commented, so you can imagine some operations here), deletes the file, and prints a message saying "File deleted" for each iteration. The os.remove() function is used to delete the files, and the with open() statement is used to create the files.
If you run this program, you will see:
In the above program, all these steps will happen so quickly that you will be sharing in disbelief whether the file creation even happened at all! In order for deletion to happen, the file creation must happen. To convince yourself, you can try uncommenting the os.remove() line and then look into your directory/folder to see the new files.
Thus in summary, there are two nice ways to delete files in Python, using either the os.remove() function or the shutil.rmtree() function. Which one is your favorite?
If you liked learning how to do file system operations using Python, learn how to list files in a directory using Python.
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.