Python: two ways to check if a file exists

Python: two ways to check if a file exists

In this article we will look at two ways to check if a file exists in Python.

In this article we will look at two ways to check if a file exists in Python.

The first, more backwards compatible way is to use the exists() method of the os.path class.

import os

print(os.path.exists('test.txt'))

The output will be True or False depending on whether or not the file exists in the path specified as a string in the exists() method.

The second, more modern way is to use the Path class of the core library pathlib.

from pathlib import Path

test_file = Path('test.txt')

print(test_file.exists())

In this case the path to the file is passed as an argument to the constructor of the Path class. The output of the exists() method again will be True or False depending on whether or not the file exists in the specified path.

This second Object-Oriented approach to file system management is recommended for the greater flexibility and organization of the code it offers.