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

Checking if a file or directory or link exists in Python

In this article, we are going to see how to check if a file, directory or a link exists using python.

Let’s see one by one

Python – Check if a path exists :

Syntax- os.path.exists(path)

The above function will return true if the path exists and false if it does not. It can take either relative or absolute path as parameter into the function.

import os

pathString = "E:\Python"

# Check for path existence
if os.path.exists(pathString):
    print("Path Exists!")
else:
    print("Path could not be reached")
Output :
Path Exists!

However we should ensure that we have sufficient user rights available to access the path.

Python – Check if a file exists :

While accessing files inside python, if the file does not exist beforehand, we will get a FileNotFoundError. To avoid these errors we should always check if a particular file exists. For that we would have to use the following function

Syntax- os.path.isfile(path)
import os

filePathString = "E:\Python\data.csv"

# Check for file existence
if os.path.isfile(filePathString):
    #If the file exists display its contents
    print("File Exists!")
    fileHandler = open(filePathString, "r")
    fileData = fileHandler.read()
    fileHandler.close()
    print(fileData)
else:
    print("File could not be found")
Output :
File Exists!
Id,Name,Course,City,Session
21,Jill,DSA,Texas,Night
22,Rachel,DSA,Tokyo,Day
23,Kirti,ML,Paris,Day
32,Veena,DSA,New York,Night

Python – Check if a Directory exists :

To check if a given directory exists or not, we can use the following function

Syntax- os.path.isdir(path)
import os

filePathString = "E:\Python\.vscode"

# Check for directories existence
if os.path.isdir(filePathString):
    # If the directory exists display its name
    print(filePathString, "does exist")
else:
    print("Directory could not be found")
Output :
.vscode does exist

Python – Check if given path is a link :

We can use isdir( ) and isfile( ) to check if a symbolic(not broken) link exists. For that we have a dedicated function in os module

Syntax- os.path.islink(path)

We will be using path.exists and path.islink together in this function so that we can check if the link exists and if it is intact.

import os

linkPathString = "E:\Python\data.csv"

# Check for link
if os.path.exists(linkPathString) and os.path.islink(linkPathString):
    print("The link is present and not broken")
else:
    print("Link could not be found or is broken")
Output :
Link could not be found or is broken

As the path we provided is not a link, the program returns the else condition.

 

Leave a Comment