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

1 Answer

0 votes
by (15.9k points)

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')

Related questions

...