We can use python to create different types of files and store them in the local computer storage. Mainly there are two types of files – binary file and text file. We can perform operations such as reading, appending, writing, and creating. While handling a given file, we want to perform certain operations only if the file exists to avoid unwanted errors. So, python must check if a file exists. There are several methods for that, and we shall be looking into these methods.
The need and types of ways to check if a file exists
We want to check if a file exists or not to avoid unwanted errors. It is important to check so as to prevent overwriting a given file. There are three main ways to check if a file exists or not. Firstly, we can check by using exception handling. The second method is by using the os module and the third way is by using the pathlib module.
Python check if file exists using Exception Handling
To check if a file exists, we can use exception handling. It is one of the simplest ways to check if a file exists. For that, we use the open() function. There are two types of exceptions which can be thrown :
First, we will look into IOError. IOError is raised when an input operation or an output operation fails. In this case, it fails because open() function was trying to access a file which does not exist. We will have a try-except block. In the try block, we shall try to open a file and when the file is not found, it will raise IOError from the except block.
try: f = open("filename.txt") f.close() except IOError: print("File not found. IOError occured.")
The output is shown below:
File not found. IOError occured.
Since no file named ‘filename.txt’ existed in the system, it showed IOError.
Another exception which we can throw is FileNotFoundError. The FileNotFoundError is raised when a file which we are trying to access does not exist in the system.
try: f = open("filename.txt") f.close() except FileNotFoundError: print("File not found. FileNotFoundError occured.")
Here the output will print the print statement from the exception since the file ‘filename.txt’ does not exist.
File not found. FileNotFoundError occured.
Python check if file exists using the OS module
The OS module present in python contains functions that are used for interacting with the operating system of the computer. There are three functions in the os module which are used for checking the existence of the file. The isfile(), isdir() and exists() function from the os.path module is used for the same. We shall be looking into each of the functions individually.
The os.path.isfile() takes the path of the file, which has to be checked as an argument. It returns a bool value that will be true if the path exists and false if it does not exist.
First, we will have to import the os module. Then we will assign the variable ‘path_name’ the path of the file. Since the below code has been executed in the colab, the path name is the filename. Finally, we will call the function os.path.exists() and pass the variable ‘path_name’ as the argument to the function.
If the file is found at the specified location, the function will return the true value, and it will print that the file exists. We can also include any further file operations which have to be executed if the file exists, in the first if condition. If the function returns a false value, it means that the file does not exist. So, it will print the second statement.
import os path_name = "filename.txt" if os.path.exists(path_name): print("File exists") else: print("File does not exist")
The output to the above code if the “filename.txt” file does not exist is:
File does not exist
The function os.path.isdir() checks a given directory to see if the file is present or not. It accepts the directory’s path as the argument and returns a boolean value depending on whether the directory exists. We have a folder in colab saved as ‘MyDirectory’. We will use os.path.isdir() to check whether that directory exists or not.
First, we will import the os module. Then, we shall specify the path_name as the name of the directory and use an if-else case to check whether that directory exists or not.
import os path_name = "MyDirectory" if os.path.isdir(path_name): print("File exists") else: print("File does not exist")
Since the folder exists, it will print ‘File exists’.
But, if we delete the folder, it will print the else statement.
File does not exist
The function os.path.exists() checks if the mentioned path exists or not. Just like the other two functions, it accepts the path as an argument and returns a boolean value.
Here, in the google colab, we have two folders – a MainFolder and a SubFolder located inside the MainFolder.
So, we will use os.path.exists() to check if the path for SubFolder exists or not.
import os path_name = "/content/MainFolder/SubFolder" if os.path.exists(path_name): print("File exists") else: print("File does not exist")
Since the file exists, it will print ‘File exists’.
Python check if file exists using the Pathlib module
The pathlib module in python is used to interact with the filesystem. There are three functions present in the pathlib module – exists(), is_file() and is_dir(). We will try all these three methods to see how they work.
This function exists() from the pathlib module checks whether a given path exists or not. First, we will import the pathlib module. Then, we shall pass the path_name as an argument to the Path() function, which shall return a value. Using that, we will call the exists() method. Here, instead of using an if-else case, we will print the function’s return value.
import pathlib path_name = "MyDirectory" p = Path(path_name) print(p.exists())
Since the path exists, the output will be True.
We will check if a given directory exists or not using the is_dir() function. We will pass the directory name as an argument to the Path() function and then with the return value, we shall call the is_dir() function.
import pathlib path_name = "/content/MyDirectory" p = Path(path_name) print(p.is_dir())
The output for an existing directory shall be:
The is_file() function shall check if the given file exists or not. Next, we shall pass the file name to the Path() function. It will return a value with which we will call the is_file() function and print is_file()‘s return value.
import pathlib path_name = "filename.txt" p = Path(path_name) print(p.is_file())
Since filename.txt exists, it will print True.
If the file would not be found, it would print False.
- You might also be interested in reading 【How to】 Check if the Variable Exists in Python.
FAQ’s on python check if file exists
The ideal method depends on your requirement. For example, if you want to check particularly for a given file, you can use the exists() method from the os and pathlib module and also through the open() method in exception handling. The other methods will check for a given directory or a given path.
That was all folks! If you have anything to share, feel free to let us know in the comments.
Till then, Keep Learning!