How to check if a file or directory exists in Python
Abstract: os.R_OK)os.R_OK)
The Python os.path
module is used for the file or directory pathename’s manipulations. The method isfile()
of this module is used to check if any file is available or not. Similarly exists()
function returns true for files and directory exists.
This tutorial includes:
- Check if file exists in Python
- Check if file is readable in Python
- Create directory if not exists in Python
For example, To test how isfile()
and exists()
functions work. Create a TestFile.py file using following content and execute it python.
- isfile() – function check if given input file exists and is a file not directory.
- exists() – function check if given input file exists. It doesn’t matter its a file or directory.
See the below examples:
import os.path print os.path.isfile("/etc/hosts") #True print os.path.isfile("/etc") #False print os.path.isfile("/does/not/exist") #False print os.path.exists("/etc/hosts") #True print os.path.exists("/etc") #True print os.path.exists("/does/not/exist") #False12345678import os.path print os.path.isfile("/etc/hosts") #Trueprint os.path.isfile("/etc") #Falseprint os.path.isfile("/does/not/exist") #Falseprint os.path.exists("/etc/hosts") #Trueprint os.path.exists("/etc") #Trueprint os.path.exists("/does/not/exist") #FalsePython >= 3.4 users can use object oriented approach to check if file exist or not. we need to import Path from the pathlib module.
from pathlib import Path fileName = Path("/etc/hosts") if fileName.is_file(): print ("File exist") else: print ("File not exist")12345678from pathlib import Path fileName = Path("/etc/hosts") if fileName.is_file(): print ("File exist")else: print ("File not exist") 2. Check if file is readableYou can also check if the file exists and is readable for the current users in Python.
import os.path if os.path.isfile('/etc/hosts') and os.access('/etc/hosts', os.R_OK): print "File exists and is readable" else: print "Either file is missing or is not readable"123456import os.path if os.path.isfile('/etc/hosts') and os.access('/etc/hosts', os.R_OK): print "File exists and is readable"else: print "Either file is missing or is not readable" #3. Python – Check if Link FileUse os.path.islink
to find if any file is a link file.
Use os.path.exists
to check if any directory exists or not and use os.makedirs
to create a directory. Below example will create directory /tmp/newdir if not exists.