Check If File Exists In Python

In this tutorial, I will be discussing different methods for how to check if file exists in python. So without wasting any time let’s get started.

Different Methods To Check If File Exists In Python

Let’s look at some methods to check if file or directory exists in python.

1. Using os.path.isfile()

os.path.file() function from the standard os library takes a path as an argument and returns a boolean after checking if it’s a file or not. here is the code for that.

# idle session to check if file exists in python
>>> import os
# Import the os library

# Correct path of file
>>> file_path = "C:\\Users\\Acer\\Desktop\\test.py"
>>> os.path.isfile(file_path) # Python Check If File Exists
True

# Path of file which did n't exists 
>>> wrong_path = "C:\\Users\\Acer\\Desktop\\test.png"
>>> os.path.isfile(wrong_path )
False

2. Using pathlib module

You can also builtin pathlib module to check if the path is valid or not. here is the code for that.

>>> import pathlib
# import the pathlib library

>>> file_path = "C:\\Users\\Acer\\Desktop\\test.py"
>>> file = pathlib.Path(file_path)
>>> file.exists() # Check if path is valid or not
True

3. Using open() Function

We can use the built-in open() function to open the file in the read mode and wrap the whole code inside the try-except block to check if the path is valid or not. here is what I mean.

def check_file(path):
    """
    Funcion to check if file exists in python
    """
    try:
        file = open(path,"r") # try to open the file in read mode
        file.close() # close the file
        # if everything went good means path is valid
        return True # so return true
    except:
        # if error occurs means file did nt exists
        return False # so return False

right = "C:\\Users\\Acer\\Desktop\\test.py"
print(check_file(right))

wrong = "C:\\Users\\Acer\\Desktop\\test.png"
print(check_file(wrong))

Here is the output of above code.

Output:

True
False

4. Using os.path.exists()

os.path.exists() can also be used to check if the path of directory or file exists or not.

>>> import os

>>> right = "C:\\Users\\Acer\\Desktop\\test.py"

>>> os.path.exists(right)
True

5. Using os.path.isdir()

os.path.isdir() function from the standard os library can be used to check if directory exists or not. here is code for that.

>>> import os

>>> os.path.isdir("C:\\Users\\Acer\\Desktop\\testfoder")
True

Summary

Here is the summery of whole tutorial in one picture.

summary of full tutorial on how to check if file exists in python

That’s wrap for the tutorial of how to check if file exists in python.

Also read about how to write list to a file in python

Leave a Reply