How to find the path of a file or directory is exists or not???

    Directory contains all the files available in the system. Each and every file is specified with a path. This blog gives the way to find the path and its existence.

First, list out all the paths available in the system by the below code.

#Import the sys module.

import sys

#print the available system paths

print(sys.path)

when executing this code, the available paths in system is displayed.

['', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages']

Finding the file path available or not by path.exists() method:

This method uses a built-in module “OS”.  Let us use the function “path.exists()” to check the path exists or not.

#First,import os module

import os

#Set the path

path ='C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311\\DLLs'

#using os.path.exists(path) function,get the value of ex.

ex = os.path.exists(path)

#if the ex is assigned to 1 means, the file exists already. Just print the value as the path exists. Else prints that the path doesnot exist.

if ex == 1 :

    print("The path exists")

else :

    print("The path doesnot exist")

The output is:

The path exists

 Finding the file exists or not by isfile() method:

              This method is used to check whether the file is available or not.

#import os module.

import os

#assign the path of the file.

path = 'C:\\raji\\blog\\avg.py'

#Find the file existence by the isfile() and assign the value to ex.

ex = os.path.isfile(path)

#If the ex value is 1, the file exists. Otherwise, it does not exist. Print the output accordingly.

if ex == 1 :

     print("The file exists")

else :

    print("The file doesnot exist")

Just execute this program. you get the below output.

Output:


Finding the directory by isdir() method:

            This method finds the directory availablitiy.

#import the built in module.

import os

#set the path of directory.

path = 'C:\\Users\\rajeswari jeevananth\\AppData\\Local\\Programs\\Python\\Python311'

#use the method isdir() to check the directory is available or not.

sdir = os.path.isdir(path)

# check the variable assigned to the function output. If true, it prints “This directory available”. Else, it prints “This directory doesn’t exist”

if sdir == 1:

   print("This directory exists")

else :

   print("This directory doesnot exist")

The output of the program is


 This is the simple way to find the path of a file or directory existence.

No comments:

Post a Comment