33
I need to check if a file or directory exists before processing it.
Loading...
Q&A · Answered
I need to check if a file or directory exists before processing it.
Accepted answer
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")Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.