Skip to content

Q&A · Answered

How to check if file exists in Python

asked 9 months, 1 week ago 972 views 1 answer
33

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

1 Answer

One accepted
24

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
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")

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.