How do I check if a file exists or not, without using the try statement?
You can follow these three ways:
Note1: The
os.path.isfile
used only for files
import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists
Note2: The
os.path.exists
used for both files and directories
import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) #True if directory exists
The
pathlib.Path
method (included in Python 3+, installable with pip for Python 2)
from pathlib import Path
Path(filename).exists()