os.remove() method in Python

Last Updated : 8 Jun, 2026

os.remove() function in Python is used to delete files from the file system. It is part of the os module, which provides tools for interacting with the operating system. This method is useful when you need to programmatically remove files during automation, cleanup tasks, or file management operations.

Note: It cannot delete directories. If the path points to a directory, a IsADirectoryError will be raised.

Example:

Python
import os

os.remove("file.txt")
print("File deleted successfully")

Output

File deleted successfully

Syntax

os.remove(path, *, dir_fd=None)

Parameters:

  • path (Required): A path-like object (string or bytes) representing the file to remove.
  • dir_fd (Optional): Refers to a directory file descriptor. Ignored if an absolute path is provided.
  • * before dir_fd means it must be specified as a keyword argument.

Return Type: This method does not return any value.

Examples of os.remove Method

Example 1: Remove a File

This example shows how to remove a specific file by constructing its path and using os.remove().

Python
import os

# File path
file = 'file.txt'
location = '/home/User/Documents'
path = os.path.join(location, file)

os.remove(path)
print(f"{file} has been removed successfully")

Output
file.txt has been removed successfully

Explanation: The code constructs the full path to file.txt and deletes it using os.remove().

Example 2: Attempting to Remove a Directory

This example demonstrates what happens when we try to remove a directory using os.remove(), which is not allowed:

Python
import os

# Path to a directory
path = '/home/User/Documents/myfolder'

os.remove(path)

Output:

Traceback (most recent call last):
...
IsADirectoryError: [Errno 21] Is a directory: '/home/User/Documents/myfolder'

Explanation: Since path points to a directory, os.remove() raises a IsADirectoryError.

Example 3: Handling Errors

This example shows how to handle errors, using a try-except block when attempting to remove a path.

Python
import os

path = '/home/User/Documents/myfolder'

try:
    os.remove(path)
    print(f"{path} removed successfully")
except OSError as e:
    print(e)
    print("File path cannot be removed")

Output
[Errno 21] Is a directory: '/home/User/Documents/ihritik'
File path can not be removed

Explanation: The code uses try-except to handle errors like missing files, invalid paths, or attempts to delete a directory.

Example 4: Delete Files With a Specific Extension

Files with a specific extension can be identified and deleted automatically using os.remove(). This is useful for cleanup tasks, such as removing temporary, log, or backup files from a directory.

Python
import os

for file in os.listdir():
    if file.endswith(".log"):
        os.remove(file)
        print(f"Deleted: {file}")

Output

1. If the directory contains the files:

Deleted: app.log
Deleted: error.log
Deleted: debug.log

2. If no .log files are present, the program will produce no output.

Explanation:

  • Uses os.listdir() to retrieve all files and folders in the current directory.
  • Iterates through each item using a for loop.
  • Checks whether a file ends with the .log extension using endswith().

Check if a File Exists Before Deleting

Before deleting a file, it's better to verify that the file exists. This helps prevent errors and ensures that the deletion operation is performed only on valid file paths.

Python
import os

path = "file.txt"
if os.path.exists(path):
    os.remove(path)
    print("File deleted successfully")
else:
    print("File does not exist")

Output
File does not exist

Explanation:

  • Defines the file path to be deleted in the path variable.
  • Uses os.path.exists() to check whether the file exists.
  • If the file exists, os.remove() deletes it from the file system.

Note: Files deleted using os.remove() are permanently removed and cannot be recovered through the Recycle Bin or Trash.

Comment