How to check if a file exists or not using Python?

You might wish to perform a specific action in a Python script only if a file or directory is present or not. For instance, you might wish to read from or write to a configuration file, or only create the file if it doesn't already exist.

There are many different ways to check if a file exists and figure out what kind of file it is in Python.

Using os Module

An inbuilt Python module called os has tools for dealing with the operating system. The os.path submodule provides two methods, isfile() and exists(), that return True or False depending on whether a file exists or not.

os.path.isfile() Method

This method determines whether the specified path contains a regular file or not ?

import os

# Check if a file exists using os.path.isfile()
filepath = 'sample.txt'

# Create a sample file for demonstration
with open(filepath, 'w') as f:
    f.write("Hello World!")

file_exists = os.path.isfile(filepath)
print(f"File exists: {file_exists}")
File exists: True

os.path.exists() Method

This method checks whether the given path exists or not (works for both files and directories) ?

import os

# Check if a file exists using os.path.exists()
filepath = 'sample.txt'

# Create a sample file for demonstration
with open(filepath, 'w') as f:
    f.write("Hello World!")

path_exists = os.path.exists(filepath)
print(f"Path exists: {path_exists}")

# Also works for directories
dir_exists = os.path.exists('.')
print(f"Current directory exists: {dir_exists}")
Path exists: True
Current directory exists: True

Using pathlib Module

The pathlib module offers an object−oriented interface for working with files and directories. It provides two main methods for checking file existence ?

pathlib.Path.exists() Method

import pathlib

# Create a sample file
filepath = pathlib.Path("sample.txt")
filepath.write_text("Hello World!")

if filepath.exists():
    print("The given file exists")
else:
    print("The given file does not exist")
The given file exists

pathlib.Path.is_file() Method

import pathlib

# Create a sample file
filepath = pathlib.Path("sample.txt")
filepath.write_text("Hello World!")

if filepath.is_file():
    print("The given file exists")
else:
    print("The given file does not exist")
The given file exists

Using glob Module

The glob module is used to find files matching a specific pattern using wildcard characters ?

import glob

# Create a sample file
with open('sample.txt', 'w') as f:
    f.write("Hello World!")

if glob.glob("sample.txt"):
    print("The given file exists")
else:
    print("The given file does not exist")

# Using wildcards to find files
python_files = glob.glob("*.py")
print(f"Python files found: {len(python_files)}")
The given file exists
Python files found: 0

Using Exception Handling

We can use try−except blocks to check file existence by attempting to open the file. If the file doesn't exist, an exception is raised ?

Using IOError Exception

# Create a sample file first
with open('sample.txt', 'w') as f:
    f.write("Hello World!")

try:
    file_handle = open('sample.txt')
    print("The given file exists")
    file_handle.close()
except IOError:
    print("The given file does not exist")
The given file exists

Using FileNotFoundError Exception

try:
    file_handle = open('nonexistent.txt')
    print("The given file exists")
    file_handle.close()
except FileNotFoundError:
    print("The given file does not exist")
The given file does not exist

Comparison of Methods

Method Files Only Directories Best For
os.path.isfile() ? ? Checking files specifically
os.path.exists() ? ? Checking any path
pathlib.Path.exists() ? ? Modern object-oriented approach
pathlib.Path.is_file() ? ? Object-oriented file checking
glob.glob() ? ? Pattern matching
Exception handling ? ? When you need to open the file anyway

Conclusion

Use os.path.exists() for simple existence checks, pathlib.Path.exists() for modern Python code, and exception handling when you plan to open the file immediately. Choose glob for pattern−based file searching.

Updated on: 2026-03-24T18:07:51+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements