0
0
PythonHow-ToBeginner · 3 min read

How to Check if File Exists in Python: Simple Methods

To check if a file exists in Python, use os.path.exists(path) or pathlib.Path(path).exists(). Both return True if the file is found and False otherwise.
📐

Syntax

There are two common ways to check if a file exists in Python:

  • Using os.path.exists(path): This function returns True if the file or directory at path exists.
  • Using pathlib.Path(path).exists(): This method returns True if the file or directory exists at the given path.
python
import os
from pathlib import Path

# Using os.path
os.path.exists('filename.txt')  # Returns True or False

# Using pathlib
Path('filename.txt').exists()  # Returns True or False
💻

Example

This example shows how to check if a file named example.txt exists in the current folder and prints a message accordingly.

python
import os

filename = 'example.txt'

if os.path.exists(filename):
    print(f"The file '{filename}' exists.")
else:
    print(f"The file '{filename}' does not exist.")
Output
The file 'example.txt' does not exist.
⚠️

Common Pitfalls

Some common mistakes when checking if a file exists include:

  • Using os.path.exists() without importing os.
  • Confusing files with directories, since exists() returns True for both files and folders.
  • Not handling cases where the path is incorrect or the program lacks permission to access the file.

To check specifically for a file (not a directory), use os.path.isfile(path) or Path(path).is_file().

python
import os
from pathlib import Path

path = 'example.txt'

# Wrong: only checks if path exists (file or folder)
if os.path.exists(path):
    print("Exists")

# Right: check if it is a file
if os.path.isfile(path):
    print("It is a file")

# Using pathlib
p = Path(path)
if p.exists():
    print("Exists")
if p.is_file():
    print("It is a file")
📊

Quick Reference

Function/MethodDescriptionReturns True For
os.path.exists(path)Checks if path exists (file or directory)File or directory exists
os.path.isfile(path)Checks if path is a fileOnly files
pathlib.Path(path).exists()Checks if path exists (file or directory)File or directory exists
pathlib.Path(path).is_file()Checks if path is a fileOnly files

Key Takeaways

Use os.path.exists() or pathlib.Path().exists() to check if a file or directory exists.
To confirm the path is a file (not a folder), use os.path.isfile() or pathlib.Path().is_file().
Always import the required modules: os or pathlib before using their functions.
Checking existence does not guarantee you can open the file; handle permissions separately.
Pathlib offers a modern, object-oriented way to work with file paths.