How Do I Check Whether a File Exists Without Exceptions?

Under How to check whether a file exists in Python without using try-except blocks you can use built-in modules like os.path or pathlib.

Summarize with AI

Not enough time? get the key points instantly.

Python provides straightforward approaches via standard libraries. These methods are concise and help you to write clean and exception-free code. 

Method 1: Using os.path.exists()

This method works across operating systems and returns True if the file (or directory) exists.

python

import os

file_path = “example.txt”

 

if os.path.exists(file_path):

    print(“File exists.”)

else:

    print(“File does not exist.”)

Works for both files and directories. Use os.path.isfile() to check specifically for files. 

Method 2: Using pathlib.Path.exists()

Introduced in python 3.4, It’s a more modern, object-oriented way to work with file paths.

python

from pathlib import Path

file = Path(“example.txt”)

 

if file.exists():

    print(“File exists.”)

else:

    print(“File does not exist.”)

Pathlib is preferred for newer codebases due to its clean syntax and better path handling. 

Also Read:

Tip

  • To check only for files (not directories) use os.path.isfile() or file.is_file() in pathlib. 
  • Avoid using try-except just to test file presence; these methods are faster and more readable.

Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

Python

How to Copy Files in Python

You can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it…