3 Best Methods to Check if File or Directory Exist in Python
Many times in program we need to handle reading and writing file. 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 for 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 going to share you three different ways of checking file and directory existence before reading or writing it.
Using…
- os Python module
- Try block
- pathlib Python module
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 files.)
Now let’s come to our topic…
How to write a code for Python check if file exists?
Here are three different methods you can use…
1.Using os Python module
The os module has method os.path.exists()
to check the file existence in the directory.
Python Check if File Exist
import os os.path.exists(test_file.txt) #True os.path.exists(no_exist_file.txt) #False
Python Check if Directory Exist
import os os.path.exists(test_dir) #True os.path.exists(no_exist_dir) #False
There can be file and directory with the same name. If you check using 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 if there is a directory with the name “test-data”, 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")
Above method will return False if there is no file “test-data”, even if the directory present with the same name.
Even if the file is present, you can find whether the file is accessible to write or to execute.
How to check if the File is Accessible to read, write or execute?
You can check the file if it is accessible for the various mode of accessing the file (ex. read, write or execute) using method os.access()
.
Syntax:
os.access(<path>, <mode>)
Along with the file path, you can provide accessible mode:
- os.F_OK: to check existence of the file path
- os.R_OK: to check if file is accessible to read
- os.W_OK: to check if file is accessible to write
- os.X_OK: to check if file is accessible to execute
This method returns True or False based on the existence of file path and permission to access the various accessible mode.
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 the very useful method if you want to check the file for particular access mode.
2. Using try Block:
You can open the file using 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 like general exception handling, you can use try block to catch the exception.
There can be many reasons if you are not able to access the file in your program.
- If you are trying to open the file which is not present it will throw an exception as
FileNotFoundError
. - If the file is present but if you don’t have permission to access it in your program, it throws an error as
PersmissionError
.
So here is a code for Python check if 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."
It is not necessary you have to handle all the exception individually. All these exceptions come under the parent exception IOError
.
So you can simply write a program to handle all the file check exception as follows…
try: f =open() #Perform File Operations (Reading and Writing a File) f.close() except IOError: print "File is not accessible."
Using try block for Python check if the file exists is very simple and graceful to handle all the exception.
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 good thing is… you don’t need to import any external module for using it.
3. Using pathlib Python module
The module pathlib
is available in Python 3. If you are using Python 2 version, you can install as 3rd party module.
First, you have to create 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 check if file exists. If you have any doubt, 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:
See you soon in next Python Tutorial!
Comments
Vernon Cole
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.
Aniruddha Chaudhari
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!
Vernon Cole
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))
Aniruddha Chaudhari
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!