To delete a file in Python three methods are used. The
os.remove() method will delete single files. The
os.rmdir() method will remove a file or directory that’s empty. Finally, 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
This tutorial will discuss how to remove Python files and folders using
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
Often, when you’re working with files, you’ll want to delete an individual file. That’s where the Python
os.remove() method comes in.
Delete a File with Python
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. 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 using
Here’s the syntax for the
import os os.remove(file_location)
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.")
The result of our code is that our file has been removed, and the following message has been printed to the console:
final_analysis.csv has been deleted.
Let’s break down our code. 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 variable called
path that stores the file path for the file we want to remove.
On the next line, we use
os.remove() and specify our
path variable as the file path, which will remove our file. Then, our program prints out a message to the console.
os.remove() method only works if you want to remove a file. Here’s an example of a program that tries to delete our folder
import os path = "/home/school/math" os.remove(path) print("/home/school/math has been deleted.")
Our code returns:
IsADirectoryError: [Errno 21] Is a directory: '/home/school/math'
Python Delete Empty Directory
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
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
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.
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 permissions 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:
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, and 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.
Python Delete Directory With Files
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
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.