Menu

Working with Files: Delete a File in Python

To delete a file in Python, import the os module and call os.remove(file_path), passing in the path of the file you want to delete. Wrap it in a try-except block to handle cases where the file doesn't exist or you lack permission to delete it.

In this "working with files" module, you have learned the following so far:

And in this article, you will be learning to delete a file in Python. Without further ado, let's get started.

Procedure to Delete a File in Python:

Let's go through the process of deleting a file in Python step by step:

  1. Import the 'os' module:  

    >>> import os
  2. Specify the file path and name:  

    >>> file_path = "path/to/file.txt"

    In this example, 'file_path' represents the path to the file you want to delete. Replace "path/to/file.txt" with the actual path and name of the file you wish to remove. If the file is located in the current working directory, you can simply provide the file name.

  3. Delete the file using 'os.remove()':  

    >>> os.remove(file_path)

    The 'os.remove()' function takes the file path as an argument and deletes the file from the file system. It permanently removes the file, so exercise caution when using this function. Once a file is deleted, it cannot be recovered unless you have a backup.

  4. Handle any exceptions:
    If the file specified by file_path does not exist, the 'os.remove()' function will raise a 'FileNotFoundError' exception. You can handle this exception using a try-except block to gracefully handle the situation. Here's an example of how you can do it:  

    >>> try:
    >>>     os.remove(file_path)
    >>>     print("File deleted successfully.")
    >>> except FileNotFoundError:
    >>>     print("File not found.")
    >>> except PermissionError:
    >>>     print("Permission denied. Unable to delete the file.")

This code will catch the specific exceptions raised when a file is not found or when there are permission issues. You can customize the error messages or add more specific exception handling as needed.

A Modern Alternative: pathlib

If you're working with pathlib elsewhere in your code, you can delete a file using Path.unlink() instead of os.remove():

python

from pathlib import Path

file_path = Path("path/to/file.txt")
file_path.unlink(missing_ok=True)

The missing_ok=True argument tells Python not to raise an error if the file doesn't exist — a handy shortcut that saves you from writing a try-except block just to handle a missing file.

Conclusion:

In conclusion, deleting a file in Python is a simple task but you have to remember to give the necessary permissions to modify files in the specified directory. Make sure to exercise caution when deleting files especially if there is sensitive data in them. It is best to double-check the file path to ensure you are deleting the intended file. If you have any questions or doubts, feel free to contact us.


Learn via Video Course

Python Programming Course: Beginner to Advanced with Certification Logo

Python Programming Course: Beginner to Advanced with Certification

6 hrs