Check whether a file/directory exists in Python

We all forget where we store our files and sometimes we forget if the file/ directory exists in our system. In this article, we are going to learn how to find a file/ directory in Python.
You might have a doubt of why we are using Python to check whether a file/directory exists or not. Python is an amazing language that supports you to do various activities haphazard-free manner and one of them is finding out if the file/ directory exists.

Initially, we need to import the os.path module. Then implement a few of its functions.

os.path Module

This module contains useful functions related to pathnames.

You can create a directory in python using OS package
In Python, these functions are used for various functions like for merging, normalizing and retrieving path names.
The next two lines of code are on importing this module-

import os.path
from os import path

Below are the ways are shown to check for a file/ directory existence-

os.path.exists()

This function(path.exists()) helps us to know quickly whether the file is present or not.
Here is the Syntax:

path.exists("data.csv")

The output of the above-given line of code is Boolean( It either stores True or False). 

Let’s now see a piece of code with the above lines mentioned-

import os.path
from os import path

print("Checking for Existence of file/ directory")
print ("File/Directory exists:"+str(path.exists('data.csv')))# This file is present in the system
print ("File/Directory exists:" + str(path.exists('Hello.txt')))# This file is not present in the system
print ("File/Directory exists:" + str(path.exists('Downloads')))
OUTPUT:
Checking for Existence of file/ directory
File/Directory exists:True
File/Directory exists:False
File/Directory exists:True

Now go ahead change the file names(in the code given) and check it on your system.

os.path.isfile()

Unlike the above function which does not distinguish between file and directory, this function detects if it’s a file(it should be present in the system) or not.

Here is the Code:

import os.path
from os import path

print ("It's a file-" + str(path.isfile('data.csv'))) #'data.csv' is a file
print ("It's a file-" + str(path.isfile('Downloads')))#'Downloads' is a directory
OUTPUT:
It's a file-True
It's a file-False

os.path.isdir()

As seen in the above two functions, path.isdir()  is used to detects if it’s a directory(it should be present in the system) or not.

Here is the Code:

import os.path
from os import path

print ("It's a Directory-" + str(path.isfile('data.csv'))) #'data.csv' is a file
print ("It's a Directory-" + str(path.isfile('Downloads')))#'Downloads' is a directory

OUTPUT:
It’s a Directory-False
It’s a Directory-True

Finally, Checking the presence of a file is easier in Python when compared to the search option in myComputer, It takes lesser time and is accurate.

Leave a Reply

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