Many times in the program we need to handle reading and writing files. I am sure you might have come across when your program crashes if the file in the directory that you want to read does not exist.
And this happens to everyone if you start learning file handling in Python.
So the only solution to avoid a crash is using “Python check if file exists or not before performing any operations on file”.
In this tutorial, I am sharing with you three different ways of checking file and directory existence before reading or writing it.
Using…
If you are new to the file handling in Python, here is a code for reading the file in Python. (This code is written to read csv file format but it works for reading any type of file.)
Now let’s come to the topic…
Here are three different methods you can use…
The os module has a method os.path.exists()
to check the file’s existence in the directory.
Python Check if File Exist
import os print(os.path.exists(test_file.txt)) #True print(os.path.exists(no_exist_file.txt)) #False
Python Check if Directory Exist
import os print(os.path.exists(test_dir)) #True print(os.path.exists(no_exist_dir)) #False
There can be a file and directory with the same name. If you check using the above methods, you can not identify whether it is a file or a directory.
Suppose you want to check if file “test-data” is present or not. In case there is a directory with the name “test-data”, the above functionos.path.exists()
will return True. This is not expected as you are interested in the file (not the directory).
To avoid this teeter, you can use the following method.
Code for Checking only Files:
import os os.path.isfile("test-data")
The above method will return False if there is no file “test-data”, even if the directory is present with the same name.
Even if the file is present, you can find whether the file is accessible to write or to execute.
You can check the file if it is accessible for the various modes of accessing the file (ex. read, write or execute) using the method os.access()
.
Syntax:
os.access(<path>, <mode>)
Along with the file path, you can provide accessible mode:
This method returns True or False based on the existence of the file path and permission to access the various accessible modes.
import os if os.access("/file/path/foo.txt", os.F_OK): print("Given file path is exist.") if os.access("/file/path/foo.txt", os.R_OK): print("File is accessible to read") if os.access("/file/path/foo.txt", os.W_OK): print("File is accessible to write") if os.access("/file/path/foo.txt", os.X_OK): print("File is accessible to execute")
This is a very useful method if you want to check the file for a particular access mode.
You can open the file using the method open()
. It checks if the file is accessible or not in your program.
Syntax for Opening the File:
open(<file/path>)
If you open the file directly without checking its existence, the program may crash. As with general exception handling, you can use a try block to catch the exception.
There can be many reasons why you are not able to access the file in your program.
FileNotFoundError
.PersmissionError
.So here is a code for Python to check if the file exists…
try: f =open() #Perform File Operations (Reading and Writing a File) f.close() except FileNotFoundError: print("File is not found.") except PersmissionError: print("You don't have permission to access this file.")
You don’t need to handle all the exceptions individually. All these exceptions come under the parent exception IOError
.
So you can simply write a program to handle all the file check exceptions as follows…
try: f =open() #Perform File Operations (Reading and Writing a File) f.close() except IOError: print("File is not accessible.")
Using a try block for Python to check if the file exists is very simple and graceful to handle all the exceptions.
Doing it more Pythonic way (as per Vernon Cole explained in the comment)…
myfilename = "my_file.txt" try: with open(myfilename) as myfile: for line in myfile: print(line.strip()) except IOError: print("Trouble using file {}".format(myfilename))
And the good thing is… you don’t need to import any external module to use it.
The module pathlib
is available in Python 3. If you are using Python 2 version, you can install it as 3rd party module.
First, you have to create a path object by passing the path of the file. This path can be a file name or directory path.
Check if the Path is Exist or not:
path = pathlib.Path("path/file") path path.exist()
Check if the Path mentioned is a file or not:
path = pathlib.Path("path/file") path path.is_file()
This is all about this tutorial for Python to check if a file exists. If you have any doubts, feel free to write in the comment section. I will reply to your every query as soon as possible.
Other File Program you can give a try to explore File handling in Python:
Happy coding!
The second example would be more clear if it were explained that the file is actually processed in the “try” block — not just opened and closed to test for accessibility.
This is more “Pythonic” — that is clearer to read and more efficient to execute — than testing for accessibility, then later opening the file. It also eliminates a possible window of time, between testing for the existence of the file and opening it for use, when an outside agent could remove the file.
Hi Vernon,
I was expecting for file processing in between file opening and closing it, though I missed commenting explicitly. Updated code by adding appropriate comment between open and close file.
Your code seems more Pythonic and I have added code snippet in the post from your comment.
Thanks Vernon for taking concern. I really appreciate.
Happy Pythoning!
I see that code markup for comments to the blog are difficult. I will use dots to replace Python white space…
myfilename = ‘my_file.txt’
try:
.. with open(myfilename) as myfile:
…. for line in myfile:
…… print(line.strip())
except IOError:
.. print(‘Trouble using file {}’.format(myfilename))
Yeah, comment section lacks for code markup configuration. I have updated your first comment with proper Python markup standard and indentation.
Thanks, Great to see you here!