How do I check whether a file exists using Python?


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

Updated on: 30-Jul-2019

481 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements