DEV Community

Cover image for How to Check if a File Exists in Python
Sameer Qaiser
Sameer Qaiser

Posted on

How to Check if a File Exists in Python

When I first started writing Python scripts that read files, I kept getting FileNotFoundError and crashing my program.

I later learned that you can check if a file exists before trying to open it using the os module.

import os

file_path = "data.txt"

if os.path.exists(file_path):
    with open(file_path, "r") as file:
        print(file.read())
else:
    print("File not found.")
Enter fullscreen mode Exit fullscreen mode

This simple check makes your scripts much more robust, especially if they depend on user-generated files or external data.

Top comments (0)