Python program to check if a path exists

How to test if a path exists or not in python:

Python os module provides a lot of utility functions for different operating system related tasks. os.path is a submodule of os and this submodule provides methods for different file path related operations.

If you want to check if a path exists or not in python, you can use the os.path.exists() method. This method is used to check if a path exists or not. Also, it is recommended to use because it is available in os.path submodule and we don’t have to install any third party library for this. Simply use import os and use it.

In this post, we will learn how to use os.path.exists with examples.

Definition of os.path.exists:

os.path.exists method is defined as below:

os.path.exists(path)

This method will check if the given path exists. It returns one boolean value. It returns True for a valid path or an open file descriptor. For broken symbolic links, it will return False.

If the permission for os.state() on a file is not given, it will return False.

We can also pass the open file descriptor for a file to this method. It will return True for valid value. This is available only for python 3.3 and above.

Starting from python 3.6, we can also provide other path like objects.

Example of os.path.exists:

Let’s take a look at the below example program:

import os

print(os.path.exists('/Users/cvc/Downloads'))
print(os.path.exists('/Users/cvc/Downloads/file.png'))
print(os.path.exists('./'))
print(os.path.exists('../../../'))
print(os.path.exists('.'))
print(os.path.exists(''))

If you run this program, it will print:

True
False
True
True
True
False

The second print statement printed False, because the file file.png doesn’t exist. The last one is not a path, so it printed False. Other than these two, it prints True for all.

As you can see in this example, we can also give relative path to os.path.exists.

Conclusion:

We learned how to use os.path.exists in python with examples. This method is pretty useful and we can use it to check if a path exist or not before trying to do any path related operations. For example, os.path.exists can be used to check if a path exists or not before reading or writing to a file. This will add an additional layer of safety before trying to open a file.

You might also like: