All Courses

How to check if the file is existing or not in python?

Shashank Shanu

2 years ago

File is existing or not | insideAIML
Table of Contents
  • Introduction
  • Method 1: Using os.path.exists() 
  • Method 2: Using os.path.isfile()
  • Method 3: Using open() and try...except


          Many times, you may want to know how you can know what are the files already exist in computer. So, the ability to check whether a file exists on disk or not is an important task for many types of Python programs.
Let’s take an example
Suppose, you want to make sure a data file is available before you try to load it, or you want to prevent overwriting an existing file. This is also true with respect to directories where you try to ensure an output folder is available before your program runs with an error.
Python consist several ways which helps us to verify a file or directory exists using some functions built using the core language and the Python standard library.
Here, in this article, you’ll see different techniques for file existence checks in Python.
Let’s do it.

Method 1: Using os.path.exists()  

          One of the most common way which is the simplest among others methods and widely used to check for the existence of a file in Python is using the exists() and isfile() methods from the os.path module in the standard library of the python programming language.
Both the above functions are available on Python 2 and Python 3.
Let’s take an example and understand how to work with the os.path.exists() function.
In the below example we are trying to check several paths such as files and directories whether it exists or not.
import os.path


output: True


output: False

In the above example we can see, when we try to call os.path.exists() it return True for files and directories as both are present in the computer. And if the file or directory does not exist it will return False.

Method 2: Using os.path.isfile()

           We can use os.path.isfile()  function to ensure that a given path points to a file and not to a directory.
import os.path

os.path.isfile (“InsideAIML_directory/myfile.txt”)

output: True

os.path.isfile (“myfile_copy.txt”)

output: False

os.path.isfile (“InsideAIML_directory”)

Method 3: Using open() and try...except

          In the above example we just saw how both the functions in the os.path module can be used to check whether a file or a folder exist or not.
Here’s in python another straightforward algorithm is present for checking whether a file exists. Here, we simply attempt to open the file with the built-in open() function, which is given below-

“[Errno 2] No such file or
directory: ‘myfile_copy.txt’ ”
If the file exists in the given path the open method will complete successfully open the file and return a valid file handle. If the file does not exist however, an error  FileNotFoundError exception will be raised:
FileNotFoundError is raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.” (Source: Python Docs)
This helps us to watch for this FileNotFoundError exception type in our own code, and use it to detect whether a file exists or not. Below is an example that will demonstrates this technique:

            file = open(“myfile.txt”)


except FileNotFoundError:

            print(“The given file does not exist”)
You may notice in the above example, how I’m immediately calling the close() method on the file object to release the underlying file handle. This is generally considered a good practice when dealing with files in Python:
If we don’t close the file handle explicitly as shown in the above example it is difficult to know when exactly it will be closed automatically by the Python runtime. It wastes system resources and can make our programs run less efficiently.
In python, another option is also available if we don’t want to close it explicitly. We use the context manager protocol and the with statement to auto-close the file.
Now, the same “just attempt to open it” technique also works for ensuring a file is both readable and accessible. Instead of watching for FileNotFoundError exceptions you’ll want to look out for any kind of IOError:

            file = open(“myfile.txt”)


except IOError:

            print(“You cannot access this file”)

print(“You can access this file”)
Now Let’s consider, if we want to use the above technique very frequently then we can create a helper function that will allow us to test whether a file exists and is accessible at the same time as show below.
def file_accessible(path,
mode= ’r’):


            Check if the file or directory at “path” can 

be accessed by the program using the

open plays equal to reading mode (r).



            file = open(path, mode)


except IOError:

            return False

return True
In python there are many more techniques available for handling different types of file. But, in this article I only explained you about two such techniques.
Now if you are planning to deal with a file in python afterwards, I would recommend that you do the existence check via the open() method and exception handling. This will help us to code better.
I hope after you enjoyed reading this article and finally, you came to know about How to work with file in python.
Like the Blog, then Share it with your friends and colleagues to make this AI community stronger. 
To learn more about nuances of Artificial Intelligence, Python Programming, Deep Learning, Data Science and Machine Learning, visit our insideAIML blog page.
Keep Learning. Keep Growing. 

Submit Review