How do I check whether a file exists using Python?

PythonServer Side ProgrammingProgramming

Presence of a certain file in the computer can be verified by two ways using Python code. One way is using isfile() function of os.path module. The function returns true if file at specified path exists, otherwise it returns false.

>>> import os
>>> os.path.isfile("d:\\Package1\\package1\\fibo.py")
True
>>> os.path.isfile("d:/Package1/package1/fibo.py")
True
>>> os.path.isfile("d:\\nonexisting.txt")


Note that to use backslash in path, two backslashes have to be used to escape out of Python string.

Other way is to catch IOError exception that is raised when open() function has string argument corresponding to non-existing file.

try:
fo = open("d:\\nonexisting.txt","r")
#process after opening file
pass
#
fo.close()
except IOError:
print ("File doesn't exist")

Published on 14-Jan-2018 19:37:21