Python Delete File: A Step-By-Step Guide (2024)

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:

import os

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 osos.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 ospath = "/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 osos.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 ospath = "/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:

Python Delete File: A Step-By-Step Guide (1)

"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 ospath = "/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 shutilshutil.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 shutilpath = "/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.

Conclusion

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.

Certainly! The concepts discussed in the article about deleting files and directories in Python involve utilizing several methods and libraries such as os, shutil, file manipulation, error handling with try and except blocks, and directory operations. Here's an overview and breakdown of each concept mentioned:

  1. os.remove():

    • This method from the os module deletes a single file.
    • Syntax: os.remove(file_location)
  2. os.rmdir():

    • Deletes an empty directory or file.
    • Syntax: os.rmdir(file_path)
  3. shutil.rmtree():

    • Removes an entire directory tree, including all files and directories within.
    • Syntax: shutil.rmtree(file_path)
  4. File Operations:

    • Python's file operations enable the creation, deletion, reading, and writing of files using various methods provided by the os and shutil modules.
  5. Error Handling with try and except:

    • Implementing error handling to manage exceptions, especially in scenarios where deleting files or directories might encounter permission issues or other errors.
    • Syntax:
      try:
       # Code that may cause an error
      except OSError as error:
       # Code to handle the error
  6. Importing Libraries (os, shutil):

    • Demonstrates how to import necessary libraries before using their functionalities.
  7. Working with Paths:

    • Defining file paths or directory paths using strings to specify the location of files or directories to be deleted.
  8. File Deletion Examples:

    • Provides practical examples demonstrating the use of os.remove(), os.rmdir(), and shutil.rmtree() to delete files and directories in Python.
  9. Concluding Summary:

    • The conclusion highlights the importance of these methods for file deletion tasks and encourages further learning in Python programming.

This comprehensive guide covers various aspects of file and directory deletion in Python, emphasizing the usage of different methods based on specific requirements. It touches upon not only the basic usage but also error handling strategies, best practices, and module imports necessary for performing these operations.

Python Delete File: A Step-By-Step Guide (2024)
Top Articles
Latest Posts
Article information

Author: Prof. Nancy Dach

Last Updated:

Views: 6533

Rating: 4.7 / 5 (77 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Prof. Nancy Dach

Birthday: 1993-08-23

Address: 569 Waelchi Ports, South Blainebury, LA 11589

Phone: +9958996486049

Job: Sales Manager

Hobby: Web surfing, Scuba diving, Mountaineering, Writing, Sailing, Dance, Blacksmithing

Introduction: My name is Prof. Nancy Dach, I am a lively, joyous, courageous, lovely, tender, charming, open person who loves writing and wants to share my knowledge and understanding with you.