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
import os print(os.path.exists('test.txt'))
The output will be
False depending on whether or not the file exists in the path specified as a string in the
The second, more modern way is to use the
Path class of the core library
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
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.