Write a Python program to check whether a 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).
In this Python file exists tutorial, we will learn how to determine whether a file (or directory) exists using Python. To check if file exists Python, we use Built-in library Python check if file exists functions.


example 1:

import os.path
open('q2.py', 'w')
print(os.path.isfile('q2.py'))

output:-
true

example 2:-
import os.path
print(os.path.exists('q2.py'))
print(os.path.exists('q3.py'))

output:-
True
False

example 3:
my_file = open('q2.py')
try:
   my_file.close()
   print("File found!")
except FileNotFoundError:
   print("File not found!")
output:-
File found!

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post