Python os.remove() Method

Python os.remove() method is used to remove (delete) a single file from the file system.

If the specified path is a directory, it raises the OSError. To remove directories, you would use os.rmdir() for empty directories or shutil.rmtree() for directories containing files.

If the file specified does not exist, it raises a FileNotFoundError.

One of the most important things to note is that deletion is permanent and cannot be undone; use this method with caution. Ensure that the file being deleted is indeed the file intended to be removed.

Syntax

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

Parameters

Arguments Description
path It is a path to the file that you want to remove.
dir_fd (optional) It is a file descriptor that refers to a directory. The default value is None.
* The “*” in the parameter list suggests all the following parameters.

Return value

It does not return any value.

Example 1: Removing a file

For this example, we will remove the dir/file.txt file.

Screenshot of a file that will be removed soon

Before removing a file, it is a good practice to check if the file exists using os.path.isfile() function.

import os

file_path = "dir/file.txt"

# Check if file exists then remove it
if os.path.isfile(file_path):
  os.remove(file_path)
  print(f"{file_path} has been removed")
else:
  print(f"{file_path} does not exist")

Output

dir/file.txt has been removed

Directory after removing a file

Example 2: FileNotFoundError

If you don’t handle file operation properly, you will get the FileNotFoundError exception.

For example, let’s say we already removed the dir/file.txt file, and now we try again to remove it, we will get the error.

import os

file_path = "dir/file.txt"

os.remove(file_path)

print(f"{file_path} has been removed")

Output

FileNotFoundError: [Errno 2] No such file or directory: 'dir/file.txt'

To handle this error, you can either use Example 1’s approach or use the try-except mechanism.

import os

# path
file_path = "dir/file.txt"

# handling the error if occurs
try:
  os.remove(file_path)
except OSError as error:
  print("File does not exist or there is some problem removing it")

Output

File does not exist or there is some problem removing it

Example 3: Removing a directory

import os

# directory path
file_path = "dir"

# try to remove a directory
os.remove(file_path)

Output

PermissionError: [Errno 1] Operation not permitted: 'dir'

You cannot remove a directory using this method.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.