You can delete files from your computer using Python. The os.remove() method deletes single Python files. os.rmdir() removes a file or a directory. The shutil.rmtree() method will delete a directory and the files contained in it.
Developers use files in Python programs for a wide array of purposes. When you’re working with files, one of the most crucial functions you need to know about is how to delete a file.
For instance, let’s say you’re creating a program that analyzes the performance of the S&P 500 index and stores the results in a file. You may want to delete any existing analysis files to make room for the new file.
In Python, you can use the os.remove() method to remove files, and the os.rmdir() method to delete an empty folder. If you want to delete a folder with all of its files, you can use the shutil.rmtree() method.
This tutorial will discuss how to remove Python files and folders using os.remove(), os.rmdir(), and shutil.rmtree(). We’ll also go through an example of each of these methods being used to delete a file or folder.
Python Delete File Tutorial
You can delete files using the Python os.remove(), os.rmdir(), and shutil.rmtree() method. These methods remove a file, a directory, and a folder with all of its files, respectively.
How to Delete a File in Python Using os.remove()
The Python os.remove() method deletes a file from your operating system. os.remove() only deletes a single file. It cannot delete a directory.
The os module allows developers to interface with the operating and file systems of a computer. os.remove() is a method included in the Python os module that allows you to delete an individual file.
Before we start working with these methods, we need to import the os library using a Python import statement.
The os library facilitates interactions with the operating system in Python. We can do so using the following code:
Now we’re ready to start removing files in Python the os.remove() module in Python. Let’s look at the syntax for the os.remove() path method:
import os os.remove(file_location)
The os.remove() method takes one parameter: the location of the file you want to delete.
Let’s say we are creating a program that analyzes the grades earned by students in a math class over the course of a year.
We want to create a file called /home/school/math/final_analysis.csv with our analyzed data. But, before our program creates that file, we first need to make sure it does not already exist.
We could use the following code to remove this file:
import os path = "/home/school/math/final_analysis.csv" os.remove(path) print("final_analysis.csv has been deleted.")
Our file has been removed. We printed the following message has been printed to the console using a Python print() statement:
final_analysis.csv has been deleted.
On the first line, we import the os module, which contains the os.remove() method that we want to reference in our program. Then, we define a Python variable called path. This variable stores the file path for the file we want to remove.
We then use os.remove() and specify our path variable as the file path, which will remove our file.
Delete Empty Directory Using Python os.rmdir()
The os.remove() method cannot be used to delete a folder. Instead, we can use the os.rmdir() method. The os.rmdir() method is used to delete an empty file or directory.
os.rmdir() accepts one parameter: the path of the file you want to delete. Here’s the syntax for the os.rmdir() method:
import os os.rmdir(file_path)
Let’s say that we have decided to store our processed data in a folder called final within our /home/school/math directory. Every time we run our program, we want to remove the final folder directory. This is because our program will create a new one with the processed data.
We could use the following code to remove the final folder:
import os path = "/home/school/math/final" os.rmdir(path) print("/home/school/math/final has been deleted.")
Our code deletes the directory /home/school/math/final and returns the following message to the console:
/home/school/math/final has been deleted.
The os.rmdir() method can only be used to delete an empty directory. If you specify a folder that contains files, the following error will be returned:
[Errno 13] Permission denied: '/home/school/math/final' Directory 'final' can not be removed
Python os Error Handling
In the above examples, we have stated that, in some cases, a permission error can be returned by an argument. If we use os.remove() to remove a directory, an error will be returned. If we use os.rmdir() to remove a directory that contains files, an error will be returned.
When you’re deleting files in a program, you may want to have a function that handles your errors gracefully if an error arises. We can do this using a try except block.
Here’s our example of the os.rmdir() method above, but with an error-handling mechanism that will print a predefined message if exceptions are raised:
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
import os path = "/home/school/math/final" try: os.rmdir(path) print("/home/school/math/final has been deleted.") except OSError as error: print("There was an error.")
Now, if we run our code and no error is returned, our directory will be removed and the following message will be returned:
/home/school/math/final has been deleted.
However, if we run our code and try to remove a directory that contains files, for example, the following message will be returned:
There was an error.
In our code, we used a try except block. This procedure first runs the lines of code within the try block. If an error is encountered, it will run the code within the except block. In this case, the except block will only be executed if an OSError is raised.
If you want to learn more about error handling using try except blocks in Python, read our tutorial on Python try except.
Delete File Python with Directories
The shutil library includes a method called shutil.rmtree() that can be used to remove a directory that contains files.
The shutil library offers a number of functions related to file operations. In our case, we want to focus on the shutil.rmtree() method, which removes an entire directory tree.
Here’s the syntax for the shutil.rmtree() method:
import shutil shutil.rmtree(file_path)
Notice that we have imported the shutil module in our code. That is because shutil.rmtree() is part of an external library, like os.remove(), so we need to import the library before we can use it.
Let’s walk through an example to show how this method can be used. Say that our grade analysis program needs to remove the directory final, but that directory already includes files with our processed data. To remove the directory and all of its files, we could use the following code:
import shutil path = "/home/school/math/final" shutil.rmtree(path) print("/home/school/math/final has been removed.")
Our code removes the folder final and all its contents, then prints the following message to the console:
/home/school/math/final has been removed.
Removing files is a common operation in Python. The os.remove() method can be used to delete a specific file, and the os.rmdir() method can be used to remove an empty directory. In addition, you can use the shutil.rmtree() method to delete a folder that contains one or more files.
To learn more about coding in Python, read our complete guide on How to Learn Python.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.