Python Check if a File or Directory Exists

Check File

import os  
os.path.isfile('./file.txt')    # True  
os.path.isfile('./link.txt')    # True  
os.path.isfile('./fake.txt')    # False  
os.path.isfile('./dir')    # False  
os.path.isfile('./sym')    # False  
os.path.isfile('./foo')    # False  

Check Directory

import os  
os.path.isdir('./file.txt')    # False  
os.path.isdir('./link.txt')    # False  
os.path.isdir('./fake.txt')    # False  
os.path.isdir('./dir')    # True  
os.path.isdir('./sym')    # True  
os.path.isdir('./foo')    # False 

Check File and Directory

import os  
os.path.exists('./file.txt')    # True  
os.path.exists('./link.txt')    # True  
os.path.exists('./fake.txt')    # False  
os.path.exists('./dir')    # True  
os.path.exists('./sym')    # True  
os.path.exists('./foo')    # False  

There are quite a few ways to solve a problem in programming, and this holds true especially in Python. Many times you’ll find that multiple built-in or standard modules serve essentially the same purpose, but with slightly varying functionality. Checking if a file or directory exists using Python is definitely

Source: Python: Check if a File or Directory Exists