PythonMastery
Python programs · Files · beginner

Check if a file exists in Python

Check whether a file or folder exists with pathlib.Path.exists(), is_file() and is_dir(), and print the file size when it does.

Path("name").exists() from the pathlib module returns True if something with that name exists. Use is_file() or is_dir() when you need to know whether it is a file or a folder.

The program

python
from pathlib import Path

# create one file and one folder to test with
Path("report.txt").write_text("Quarterly report", encoding="utf-8")
Path("photos").mkdir()

for name in ["report.txt", "photos", "missing.txt"]:
    path = Path(name)
    if path.is_file():
        print(f"{name}: file, {path.stat().st_size} bytes")
    elif path.is_dir():
        print(f"{name}: folder")
    else:
        print(f"{name}: not found")
output
report.txt: file, 16 bytes
photos: folder
missing.txt: not found

How it works

The os.path way

Older code uses the os.path module. It does the same checks with functions:

python
import os

with open("report.txt", "w", encoding="utf-8") as f:
    f.write("Quarterly report")

print(os.path.exists("report.txt"))
print(os.path.isfile("report.txt"))
print(os.path.getsize("report.txt"))
print(os.path.exists("missing.txt"))
output
True
True
16
False

If you check only so that you can open the file next, use try / except FileNotFoundError instead. Another program could delete the file between your check and your open(), and try handles that case too.

Learn the idea: File I/O, Pathlib, and Large Files, Files: Reading and Writing to Disk

A longer explanation: How do I check if a file exists in Python?