How to check if file exists in python / 4 ways to check if file exists in python

Many times a program tries to read from a file but the file has been removed or deleted from its location. Result is that the program crashes abnormally.
Best way to handle such situations is to ensure that file exists before beginning any file related operations. This post will list out methods that can be used in python to check for file existence.


Method 1: Using os.path.isfile function
os.path module has an isfile function that takes the path of the file in string format. It returns True if the file exists at the specified path and False if the file is not present or the path is a directory.

import os
 
is_file = os.path.isfile('F:/python/app.py')
if is_file:
    print('File exists')
else:
    print('File does not exist')
If you want to check for a directory, then use isdir function of os.path module.

Method 2: Using os.path.exists function
Similar to above method, exists function of os.path module accepts a path as argument and returns True if the path exists, False otherwise.
Note that isfile also checks whether the supplied path is a file or a directory and returns True when the path belongs to a file but exists function just checks if the supplied path is valid.
Example,

import os
 
is_file = os.path.exists('F:/python/app.py')
if is_file:
    print('File exists')
else:
    print('File does not exist')

exists function returns False for a dangling symbolic link. If the supplied path points to another file but the target file does not exist then the path is a dangling symbolic link.


Method 3: Using try-except block
Open a file in read mode using open function and enclose it in a tryexcept block.
If the file does not exist, then a FileNotFoundError will be thrown which means that the file does not exist. Example,

is_file = True
try:
    # open file for reading
    file_object = open('f:/python/app.py', 'r')
    # close file
    file_object.close()
except FileNotFoundError:
    # file not found
    is_file = False
 
if is_file:
    print('File exists')
else:
    print('File does not exist')

Check this to learn how to read file line by line in python.


Method 4
: Using Path object

Use Path object from pathlib module to check for the existence of a file. is_file method of Path object accepts a string path as argument and returns True if the file at the supplied path exists.
It returns False if the file does not exist or it is a broken(or dangling) symlink.

from pathlib import Path
 
# create object of Path
path_object = Path('f:/python/app1.py')
if path_object.is_file():
    print('File exists')
else:
    print('File does not exist')

This method can only be used from Python 3.4 and above since pathlib module was introduced in Python 3.4.
Hope this post made you learn something new. Keep visiting!!!

0

Mark Your Impression

Close Menu