Check if file or folder is present

file_system_check_if_present

Skill - Check if file or folder is present

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


In this post, we will learn to check if a file or folder exists

Check if a file exists using ‘isfile’ function

# import the os.path module in order to use isfile function
import os.path

# specify the file we desire to check
fPath = r'C:\Users\Nagasudhir\Documents\Python Projects\substation_pmu_dict_synthesis\index.py'

# use isfile function
isFilePresent = os.path.isfile(fPath)
if isFilePresent:
	print('File is present!!!')
else:
	print('File does not exist...')

Check if a folder exists using ‘isdir’ function

# import the os.path module in order to use isdir function
import os.path

# specify the folder we desire to check
fPath = r'C:\Users\Nagasudhir\Documents\Python Projects'

# use isdir function
isFolderPresent = os.path.isdir(fPath)
if isFolderPresent:
	print('Folder is present!!!')
else:
	print('Folder does not exist...')

Video

The video for this post can be seen here

Online Interpreter

Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://www.tutorialspoint.com/execute_python_online.php

References


Table of Contents

Comments