How to check if file exists in Python
Answered
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
Gold
•
255 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer