Python os.path.exists: The Complete Guide

When you are working with a remote server, you often need to check if the directory or file exists in the server or not. Python provides an OS module that deals with the file system.

The os.path module also provides the following functions for working with pathnames. The module is available for both Python 2 and 3.

In the context of this tutorial, the most important functions are:

  1. os.path.isfile(path) – It returns True if the path is a regular file or a symlink to a file.
  2. os.path.isdir(path) – It returns True if the path is a directory or a symlink to a directory.

But in this tutorial, we will only see the os.path.exists() function.

Python os.path.exists

The os.path.exists() is a built-in Python method used to check whether the specified path exists or not. The os.path.exists() function is also used to check whether the given path refers to the open file descriptor or not. 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

Now, 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 for this tutorial.

Leave a Comment

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