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.
os.pathmodule has an
isfilefunction that takes the path of the file in string format. It returns
Trueif the file exists at the specified path and
Falseif 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')
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,
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.
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.
Open a file in read mode using
openfunction and enclose it in a
If the file does not exist, then a
FileNotFoundErrorwill 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
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.
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!!!