Python os.path.exists() Method

The os.path.exists() is a built-in Python method that checks whether the specified path exists. The function is also used to check whether the given path refers to the open file descriptor.

To check if the file or directory exists in Python, use the os.path.exists() method.

Syntax

os.path.exists(path)

Parameters

The os.path.exists() method accepts the path as a parameter representing a file system path.

Return Value

The os.path.exists() method returns a Boolean value of class bool. The os.path.exists() method returns True if the path exists; otherwise returns False.

Example

To use the path.exists() method, import the OS module at the top of the file. 

import os

Use the path.exists() function to check whether a file or folder exists.

import os

path = "/Users/krunal/Desktop/code/"

is_exist = os.path.exists(path)

print(is_exist)

Output

True

As you can see, the path exists in the file system, which is why it returns True.

The os.path.exists() function may return False if permission is not granted to execute os.stat() on the requested file, even if the path exists.

That’s it.

Leave a Comment

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