What is the os.remove() method in Python?

Overview

The os.remove() method in Python is used to remove a file at a specified path. If the specified path is of a directory, this method raises an OSError exception.

Syntax

os.remove(filePath)

Parameters

This method accepts the following parameter:

  • filePath: This is the path of the file.

Example

Let’s look at an example of the os.remove() method in the code snippet below:

# Import the OS module
import os
# File path
filePath = 'demo.txt'
# Remove the file
os.remove(filePath)

Explanation

  • Line 2: We import the os module.
  • Line 5: We declare a variable filePath that contains the file path.
  • Line 8: We use the os.remove() method to remove the file from the directory.

Free Resources