Check if File Exists in Python

Python – Check if file exists

To check if a file exists in Python, you can use the os.path library. Import os library, call the os.path.exists() function and pass the path to file as argument to the function.

The syntax to call os.path.exists() function to check if a file exists

import os


The function exists() returns a boolean value of True if the file exists, or False if the file does not exist.


In the following program, we check programmatically if the file data.txt exists or not using os.path.exists() function.


We use the function call os.path.exists() as a condition in the if-else statement.

Python Program

import os

path_to_file = 'myfolder/data.txt'

if os.path.exists(path_to_file):
    print("File exists.")
    print("File does not exist.")


File exists.


In this tutorial of Python Examples, we learned how to check if a file exists or not using os.path.exists() function, with the help of examples.

⫷ Previous tutorialNext tutorial ⫸