How to delete a file or folder

Posted in Python by Dirk - last update: Feb 02, 2024

Summary

The easiest way to delete files and/or folders in Python is using the built-in functions os.remove() / os.unlink() for files and os.rmdir() for directories.

Note: When removing files or directories programmatically, it’s essential to handle errors gracefully, check for the existence of files or directories before attempting to delete them, and, in some cases, prompt the user for confirmation to avoid accidental data loss.

Methods

import os

file_path = "example.txt"
os.remove(file_path)

os.remove() is used to delete a single file. os.unlink() is an alternative name for the same function.

It doesn’t delete directories, only individual files. No additional dependencies are required.

In Python, os.remove() and os.unlink() are two functions that are used interchangeably for the same purpose - to delete or remove a file. There is no practical difference between them; they are just two different names for the same function.

Both os.remove() and os.unlink() functions are part of the os module, and they are used to delete a single file.

os.remove() with try-except for FileNotFoundError

This method uses a try-except block to handle the case where the file to be deleted does not exist. It’s a defensive approach to prevent the program from crashing if the file is not found.

import os

file_path = "example.txt"
try:
    os.remove(file_path)
except FileNotFoundError:
	# handle the error
    print(f"File '{file_path}' not found.")

os.rmdir()

os.rmdir() can be used to remove an empty directory. If the directory is not empty, it will raise an OSError.

import os

folder_path = "example_folder"
os.rmdir(folder_path)

shutil.rmtree()

shutil.rmtree() removes a directory and its contents recursively. It will delete the specified folder and all of its subfolders and files.

Is is part of the built-in shutil module. It should be used with caution, as it permanently deletes files and folders.

import shutil

folder_path = "example_folder"
shutil.rmtree(folder_path)

send2trash

send2trash is small package that needs to be installed before using it. It doesn’t delete the file right away but sends the file or folder to the operating system’s trash or recycle bin instead of permanently deleting it. It provides a safer option as items can be restored from the trash.

Install:

pip install send2trash

Use:

from send2trash import send2trash

file_path = "example.txt"
send2trash(file_path)

pathlib.Path.unlink() is part of the pathlib module (included in Python as of version 3.4) and is used to remove a file. It provides an object-oriented approach for file and path manipulation

Note: For Python 3.3 and earlier, easy_install pathlib or pip install pathlib should do the trick.

from pathlib import Path

file_path = Path("example.txt")
file_path.unlink()

Common Use cases

Routine system maintenance tasks often involve cleaning up old files, logs, or backups to optimize disk space and improve system performance.

When removing files or directories programmatically, it’s essential to handle errors gracefully, check for the existence of files or directories before attempting to delete them, and, in some cases, prompt the user for confirmation to avoid accidental data loss.

There are several common use cases in programming where you need to remove files or directories. Here are some examples:

1. Temporary Files:

Many programs create temporary files during their execution for various purposes. These files are often no longer needed once the program has completed its task, and they should be removed to free up disk space.

2. Data Cleaning:

When working with datasets or files, you might need to clean up or delete unnecessary or obsolete files as part of a data preprocessing or cleanup process.

3. Logging:

Logging systems often create log files to store information about program execution. Over time, these log files can accumulate, and it may be necessary to remove older log files to prevent excessive disk usage.

4. Output Management:

Programs that generate output files, reports, or results may need to remove or overwrite existing files to ensure that the latest data is available and to avoid confusion.

5. Caching:

Applications often use caching mechanisms to store temporary data for performance improvement. Cached files may need to be periodically removed or refreshed to ensure the system operates with the latest data.

Other articles