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

Shashank Shanu

a year ago

Check If The File Is Existing Or Not
Check If The File Is Existing Or Not
Many times, you may want to know how you can know what are the files already exist in a 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 of several ways which help 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() and os.path.isfile()

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
os.path.exists(“InsideAIML_directory/myfile.txt”)

output: true

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

output: false

os.path.exists(“InsideAIML_directory”)
output: true
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.
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”)
output: false

Method 2: 

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-
Open(“myfile_copy.txt”)
FileNotFoundError:

“[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 filehandle. 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 demonstrate this technique:
try:
	file = open(“myfile.txt”)
	
file.close()

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 filehandle. This is generally considered a good practice when dealing with files in Python:
If we don’t close the filehandle 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 a 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:
try:
	file = open(“myfile.txt”)
	
file.close()

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 shown below.
def file_accessible(path, mode= ’r’):

	“””
	Check if the file or directory at “path” can 
be accessed by the program using the “mode” 
open plays equal to reading mode (r).

“””
try:
	file = open(path, mode)
	
file.close()

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 to 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 the file in python.
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.

Submit Review