About
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.
Popular Classes
Scratch Coding
Minecraft Coding
TinkerCAD
Roblox Studio
Python for Kids
Javascript for Kids
Pre-Algebra
Geometry for Kids
Copyright @ Kodeclik 2024. All rights reserved.
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.
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).
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.
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.
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.
import os
fp = "path_to_your_file"
if os.path.exists(fp):
os.remove(fp)
else:
print("The file does not exist")
import shutil
fp = "path_to_your_file"
shutil.rmtree(fp)
import shutil
fp = "path_to_your_file"
try:
shutil.rmtree(fp)
except Exception as e:
print(f'Failed to delete the file: {e}')
import os
for i in range(1, 6):
file_name = f'city{i}.txt'
with open(file_name, 'w') as file:
print(f'File {file_name} created')
# do something with this file
os.remove(file_name)
print(f'File {file_name} deleted')
File city1.txt created
File city1.txt deleted
File city2.txt created
File city2.txt deleted
File city3.txt created
File city3.txt deleted
File city4.txt created
File city4.txt deleted
File city5.txt created
File city5.txt deleted