How to check if file exists in Python

Answered
Jan 05, 2026 496 views 1 answers
33

I need to check if a file or directory exists before processing it.

Y
Asked by youssef_net
Platinum 311 rep

1 Answer

24
from pathlib import Path

# Using pathlib (recommended)
path = Path('/path/to/file.txt')
if path.exists():
    print("File exists")
if path.is_file():
    print("It's a file")
if path.is_dir():
    print("It's a directory")

# Using os.path
import os
if os.path.exists('/path/to/file.txt'):
    print("Exists")
if os.path.isfile('/path/to/file.txt'):
    print("It's a file")
N
Answered by noor_code 1 week, 2 days ago
Gold 255 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.