Check file or directory exists
You can follow these three ways:
Note1: The
os.path.isfile
used only for files
import os.pathos.path.isfile(filename) # True if file existsos.path.isfile(dirname) # False if directory exists
Note2: The
os.path.exists
used for both files and directories
import os.pathos.path.exists(filename) # True if file existsos.path.exists(dirname) #True if directory exists
The
pathlib.Path
method (included in Python 3+, installable with pip for Python 2)
from pathlib import PathPath(filename).exists()