+2 votes
in Programming Languages by (73.8k points)
How to check if a file exists in a directory before doing any operation on the file?

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

There may be several ways to check whether or not a file exists. You can try one of the following two methods:

Method 1:

try:
    fh = open('/path/to/your/file' , 'r')
except:
    fh = None

if (fh is not None):
    #perform operations on your file
else:
    print ('File does not exist')

Method 2:  

import os
if (os.path.isfile('/path/to/your/file')):
    #perform operations on your file
else:
    print ('File does not exist')


...