Python Check If file Exists or Not

Last Updated On Saturday 13th Nov 2021

Python Check If file Exists

  • Python exists() method is used to check whether specific file or directory exists or not.
  • It is also used to check if a path refers to any open file descriptor or not. * It returns boolean value true if file exists and returns false otherwise.
  • It is used with os module and os.path sub module as os.path.exists(path).

os.path.exists()

Using path.exists you can quickly check that a file or directory exists.

	import os.path
from os import path

def main():

   print ("Students File Exists:"+str(path.exists('students.txt')))
   print ("Second Students Exists:" + str(path.exists('second.students.txt')))
   print ("Teachers Directory Exists:" + str(path.exists('teachers')))

if __name__== "__main__":
   main()
	
	# Students File Exists: True
# Second Students Exists: False
# Teachers Directory Exists: False
	

Check If File Exists

Python isfile()

  • The Python isfile() method is used to find whether a given path is an existing regular file or not.
  • It returns a boolean value true if the specific path is an existing file or else it returns false.
	import os.path
from os import path

def main():
    print (str(path.isfile('students.txt')))
    print (str(path.isfile('Teachers')))
if __name__== "__main__":
    main()
	
	# True
# False
	

Python File Exists

os.path.isdir()

Want to confirm that a given path points to a directory ? use path.isdir()

	import os.path
from os import path

def main():

   print (str(path.isdir('students.txt')))
   print (str(path.isdir('Teachers')))

if __name__== "__main__":
   main()
	
	# False
# True
	

Check If File Exists Python

pathlibPath.exists()

  • pathlib Module for handling with file system path.
  • It used object-oriented approach to check if file exist or not.
	import pathlib
file = pathlib.Path("students.txt")
if file.exists ():
    print ("Yes Exist")
else:
    print ("Oops!! Not Exists")
	
	# Yes Exist