Python Check If File or Directory Exists

Python Check If File or Directory Exists

Table of Contents

While working with the files or directories sometimes we need to apply a check function that checks whether the specific file or directory exists or not. In Python there are many built-in functions to check this. Following are some functions to check whether the file exists or not.

  • os.path.exists() (is used for both file or directory)
  • os.path.isfile()
  • os.path.isdir()
  • pathlibPath.exists()

Let’s take a look at them one by one.

os.path.exists()

This function returns true if the file exists else it returns false. Let’s take a look at code.

We need to import the os.path module to use the exist function.

import os.path
from os import path

Let’s take a look when the file exists.

import os.path
from os import path
print(path.exists(“secondFile.py”))
Python Check If File or Directory Exists

When the file is not present the following will be the output.

Python Check If File or Directory Exists

os.path.isfile()

We can utilise the isfile command to verify whether a provided input is a file or not. 

import os.path
from os import pathprint (path.isfile(‘secondFile.py’))
Python Check If File or Directory Exists

os.path.isdir()

If you want to verify that a given path leads to a directory, we can utilise the os.path.dir() function. Let’s take a look at the code.

In the code below, we are trying to access the file rather than a directory that’s why it is returning false.

import os.path
from os import path
print (path.isdir(‘secondFile.py’))
Python Check If File or Directory Exists

When we will try to access the folder then it will return true.

pathlibPath.exists()

We can also use the pathlib.exist() function to check both the file and directory. Let’s take a look at the code.

import pathlib
file = pathlib.Path(“secondFile.py”)
if file.exists ():
print (“File exist”)
else:
print (“File not exist”)

The following is the output.

Python Check If File or Directory Exists

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class