How to check if a file exists in Python? We have learned to perform various operations on a file in our previous file handling tutorials including reading, writing, deleting as well as copying a file in Python. But, before we perform any of these operations on a file, checking whether the file already exists or not is necessary.
If a file does not exist, then neither can we read from it nor copy or delete it. Even while writing, the user may want to check the existence of a file to avoid overwriting information.
Let us proceed into the topic and look at some methods to check the existence of a file.
Methods to check if a file exists in Python
We can check if a file exists in Python using the different methods mentioned below.
1. Using pathlib module
pathlib module in Python comes with some interesting methods like
exists(), etc. Let us look at some examples one by one:
import pathlib path = pathlib.Path('file.txt') print("pathlib-exists()---->",path.exists()) print("pathlib-is_file()---->",path.is_file()) print("pathlib-is_dir()---->",path.is_dir())
pathlib.Path()returns a path object which leads to the file name specified, which is stored in the variable ‘path‘,
pathlib.exists()method checks whether the path provided leads to a valid file or not. In our case, as file.txt’s path exists, the outcome is true.
is_file()method, on the other hand, checks whether the path object is the file. Which in our case is true as we can see in the output.
is_dir()method checks if the supplied path is any directory. Here, since our file.txt path is not a directory we get the above output.
2. Using the os module
One of the vastly used methods for checking file existence is the os.path module from the standard python library. It comes with some basic methods like
exists() similar to that of the pathlib module. Let take a closer look at one example:
import os.path print("os.path-exists()---->",os.path.exists('file.txt')) print("os.path-isfile()---->",os.path.isfile('file.txt'))
- Similar to the pathlib modules
os.exists()as well as
os.isfile()also do similar checking respectively.
- The only difference being the fact that the pathlib module brings in some great object-oriented approach and treats the path as a path object instead of a string(in case of os module).
3.Using exception handling
Let’s now have a look at a few different methods to check if a file exists in Python using exceptions.
This time we are going to use the built-in
open() function to open a file and check for an exception which if raised, will confirm that the file doesn’t exist or is inaccessible. For example:
My_file=open('file.txt') try: My_file.close() print("File found!") except FileNotFoundError: print("Files couldn't be opened!")
- In the above-given code since file.txt existed in our system,
FileNotFoundErrorisn’t raised and successfully the file gets closed.
Again, when no-file.txt doesn’t exist on our machine:
try: My_file=open('no-file.txt') My_file.close() print("File found!") except FileNotFoundError: print("Files couldn't be opened!")
- So we can clearly see that when the file isn’t found the exception
Further, the same task can be achieved with the
IOError which checks if the file being opened is readable and accessible to the program. For example, consider the following code snippet:
try: My_file = open('no-file.txt') My_file.close() print('File is found!') except IOError: print('IOError encountered!')