python how to check if file exists or not / directory exists or not

we know than python is the most exposing programming language in the artificial intelligence world ,so many of the using python as the primary programming language for building their applications,in some application we may come across a situation to check whether the file exists or directory exists using python. so in this section let see in python how to check if file exists or not / directory exists or not, fortunately we have python OS library function to check if file exists or not / directory exists or not. os.path.isdir is used in python to check if directory exists and os.path.exists() is used in python to check if file exists or not.

Lets See the Syntax
1) os.path.isdir() it return True or False based on if directory exists or not

#pythontest.py

import os 
print(os.path.isdir("D:/testvs"))    // Already one directory exists
print(os.path.isdir("D:/testvs2020"))  // directory not exists

OUT PUT

True
False



In python how to check if file exists or directory exists

2) os.path.exists() it return True or False based on if file exists or not

#pythontest.py


import os
print(os.path.exists("D:/testvs2020/pythontest.py"))
print(os.path.exists("D:/testvs/pythontest.py"))

OUT PUT

False
True


In python how to check if file exists or not

See All answers

Leave a Reply to otva Cancel reply

Your email address will not be published. Required fields are marked *

Our Tool : hike percentage calculator