How to check if a file or directory or link exists in Python ?

In this article we will discuss techniques in python to check if a file exists or a link or a directory exists or not.

Python – Check if a path exists

Python’s os module provides a function to check if a given path exists or not i.e.

os.path.exists(path)

It will True if the path exists else it will give False. Parameter path can be a relative or an absolute path.
For example,
pathStr = '/home/varun/temp'

# Check if path exists or not
if os.path.exists(pathStr) :
    print("Path " , pathStr, " exists")
else:
    print("Path " , pathStr, " does not exists")    

Some Points to remember:

  •  In case path is of a symbolic link and link is broken i.e, file it points too doesn’t exists, then it will return False.
  • It can also return False if we don’t have permission to read the entity at given path.

With os.path.exists(path) we can make sure that given path exists or not but we can not make sure if it’s a file or directory or link.

Python – Check if a file exists

Python’s os module provides a function to check if a given file exists or not i.e.

os.path.isfile(path)

It will return True if given path points to a file and that exists.

Advertisements

Why we need to check if a file exists ?

Suppose we want to open a file but if that file doesn’t exists then it will throw error FileNotFoundError at runtime i.e.

FileNotFoundError: [Errno 2] No such file or directory: ‘/home/varun/temp/sample1.csv’

To avoid this kind of error, we should first check if file exists or not. Let’s see how to do that i.e.

fileName = '/home/varun/temp/link.csv'
# Check if given path exists and it is a file
#if os.path.exists(fileName) and os.path.isfile(fileName):
if os.path.isfile(fileName):
    # File exists, so now we can safely open the file    
    fileHandler = open(fileName , "r")
    allData = fileHandler.read()
    fileHandler.close()
    print(allData)
else:
    # File does not exist
    print("File Not Found")

Python – check if a Directory exists

Python’s os module provides a function to check if a given directory exists or not i.e.

os.path.isdir(path)

It will return True if given path points to a directory and that exists.

Example,

dirName = '/home/varun/temp22'

# Check if given path exists and it is a directory
if os.path.isdir(dirName):
    print(dirName ,  ' exists and it is  a Directory' )
else:
    # File does not exist
    print("Directory Not Found")

Both os.path.isdir() & os.path.isfile() returns True in case of symbolic links too (not broken). But we have another API to check separately if given path is a link or not.

Python – check if given path is a link

On the similar lines, Python’s OS module provides a function to check if a given path is a link that exists i.e.

os.path.islink(path)

It will return True if given path points to a link, even if that is broken.

To check if given path is a link and that is not broken i.e. file/dir it points to exists, we need to use exists() along with islink() i.e.

linkPath = '/home/varun/temp/link.csv'
    
# Check if given path is link
if os.path.exists(linkPath) and os.path.islink(linkPath):
    print(linkPath ,  ' is a link and not broken' )
else:
    # File does not exist
    print("link Not Found or broken")    

Complete example is as follows,
import os

def main():
    
    
    
    print("***** Check if a given path exists *****")
    
    pathStr = '/home/varun/temp'
    
    # Check if path exists or not
    if os.path.exists(pathStr) :
        print("Path " , pathStr, " exists")
    else:
        print("Path " , pathStr, " does not exists")    
    
    
    print("***** Check if a file exists *****")
    
    
    fileName = '/home/varun/temp/link.csv'
    # Check if given path exists and it is a file
    #if os.path.exists(fileName) and os.path.isfile(fileName):
    if os.path.isfile(fileName):
        # File exists, so now we can safely open the file    
        fileHandler = open(fileName , "r")
        allData = fileHandler.read()
        fileHandler.close()
        print(allData)
    else:
        # File does not exist
        print("File Not Found")
    
    print("***** Check if a Directory exists *****")
    
    dirName = '/home/varun/temp22'
    
    # Check if given path exists and it is a directory
    if os.path.isdir(dirName):
        print(dirName ,  ' exists and it is  a Directory' )
    else:
        # File does not exist
        print("Directory Not Found")
    
    
    print("***** Check if a link exists *****")
        
    linkPath = '/home/varun/temp/link.csv'
        
    # Check if given path is link
    if os.path.exists(linkPath) and os.path.islink(linkPath):
        print(linkPath ,  ' is a link and not broken' )
    else:
        # File does not exist
        print("link Not Found or broken")    
    
if __name__ == '__main__':
    main()


Output:
***** Check if a given path exists *****
Path  /home/varun/temp  exists
***** Check if a file exists *****
Hello
Hi

***** Check if a Directory exists *****
Directory Not Found
***** Check if a link exists *****
/home/varun/temp/link.csv  is a link and not broken

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top