Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to delete a file in Python

Getting Started

Whether you're dealing with data processing, automation, or simply want to tidy up some directories, being able to delete a file in Python is a skill that will come in handy time and again. Today, we're going to learn just that.

Understanding Files and Directories

Think of your computer as a massive digital filing cabinet. Each drawer in this cabinet is a directory, and each piece of paper within the drawer is a file. To locate a file, you need to know which drawer (directory) it's in. In Python, we use a similar approach when working with files and directories.

The os Module

Python provides a built-in module called os that provides a way of using operating system dependent functionality. This includes creating, reading, updating, and deleting files. In this tutorial, we'll be using the os.remove() and os.unlink() functions to delete files.

Deleting a File with os.remove()

Here's a basic example of how you can delete a file using os.remove().

import os

# specify the file path
file_path = "/path/to/your/file.txt"

# delete the file
os.remove(file_path)

In this code, we first import the os module. Next, we define the path of the file we want to delete as file_path. Finally, we call os.remove() with file_path as the parameter to delete the file.

Handling Errors

What happens if we try to delete a file that doesn't exist? Let's find out.

import os

# specify the file path
file_path = "/path/to/your/nonexistent/file.txt"

# delete the file
os.remove(file_path)

Running this code will raise a FileNotFoundError. This is Python's way of saying, "Hey, I can't find the file you're asking me to delete!" To handle this, we can use a try/except block.

import os

# specify the file path
file_path = "/path/to/your/nonexistent/file.txt"

# delete the file
try:
    os.remove(file_path)
except FileNotFoundError:
    print("The file does not exist!")

When Python encounters a code block within a try statement, it attempts to execute it. If it encounters an error, it will stop executing the try block and move to the except block and execute that instead.

os.unlink() is another function for deleting files and it works exactly the same way as os.remove(). Here's how you can use it:

import os

# specify the file path
file_path = "/path/to/your/file.txt"

# delete the file
os.unlink(file_path)

Checking If a File Exists Before Deletion

To avoid FileNotFoundError, it's a good practice to check if a file exists before trying to delete it.

import os

# specify the file path
file_path = "/path/to/your/file.txt"

# check if file exists then delete it
if os.path.isfile(file_path):
    os.remove(file_path)
else:
    print("The file does not exist!")

Here we used os.path.isfile(file_path) which returns True if file_path is an existing regular file.

Wrapping Up

Congratulations! You've just learned how to delete files in Python. It's like having a digital shredder in your coding toolbox. Remember, with great power comes great responsibility. Always double-check the files you're deleting to avoid any unintended loss of data. Happy coding!