How to Check if a File Exists in Python

Before Python 3.4, os.path.isfile() is the way to check whether a file exists; but from Python 3.4, it introduces an object-oriented approach in pathlib module for file existence check.

os.path.isfile()

import os
fileName = r"C:\Test\test.txt"
os.path.isfile(fileName)

It checks whether the file fileName exists.

Warning

Some developers prefer to use os.path.exists() to check whether a file exists. But it couldn’t distinguish whether the object is a file or a directory.

import os
fileName = r"C:\Test\test.txt"
os.path.exists(fileName)
#Out: True
fileName = r"C:\Test"
os.path.exists(fileName)
#Out: True

Therefore, only use os.path.isfile if you want to check if the file exists.

pathlib.Path.is_file()

Since Python 3.4, it introduces an object-oriented method in pathlib module to check if a file exists.

from pathlib import Path

fileName = r"C:\Test\test.txt"
fileObj = Path(fileName)
fileObj.is_file()

Similarly, it has also is_dir() and exists() methods to check whether a directory, or a file or directory exists.