remove() function of os module in Python

The remove() function from the os module of Python removes a file as specified by a file path. If the file path is not found a FileNotFoundError exception is raised.

Os Updated 27 Mar 2023 1 min read

Overview

  • The remove() function removes a file, as specified by a given file path. The function does not work, if the file path denotes a directory.

Example

python
# Example Python program that removes

            # a file path from the operating system

            # using the os.remove() function

            import os

# File to be removed

            filePath = "/ex/marked1.txt"

try:

                # Remove the file path

                retVal = os.remove(filePath)

                print("Removed: %s"%filePath)

            except FileNotFoundError:

                print("Given file path not found")

Output

Output
Removed: /ex/marked1.txt

If the file path /ex/marked1.txt is not available then the output will be

Output
Given file path not found