There are different ways to verify a file or Python check if directory exists, using functions as listed below.

How to Check If a File Exists in Python using os.path.exists() os.path.isfile() os.path.isdir() pathlibPath.exists()

How to Check If a File Exists in Python using os.path.exists()

Using path.exists you can quickly check that a file or directory exists. Here are the steps for Python check file exists or not: Before you run the code, it is important that you import the os.path module. Steps 2) Use path.exists() funtion Now, use the path.exists() function to Python check if a file exists. Steps 3) Run the code given below Here is the complete code In our case only file guru99.txt is created in the working directory Output: File exists: True File exists: False directory exists: False

os.path.isfile()

We can use the isfile command to check whether a given input is a file or not. Output: Is it File? True Is it File? False

os.path.isdir()

If we want to confirm that a given path points to a directory, we can use the os.path.dir() function Output: Is it Directory? False Is it Directory? True

pathlibPath.exists() For Python 3.4

Python 3.4 and above versions have pathlib Module for handling with file system path. It uses object-oriented approach to Python check if folder exists or not. Output: File exist Complete Code Here is the complete code Output: Item exists: True Item is a file: True Item is a directory: False Also Check:- Python Tutorial for Beginners: Learn Programming Basics [PDF]