≡ Menu

Python: Find Out If a File Exists or Not Using isfile() Function

How can I check if a file called /etc/resolv.conf exists or not using Python program?

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Estimated completion timeN/A

You need to import os module and use os.path.isfile(file-path-here).

This function return True if "file-path-here" is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path. File path can be expressed using posixpath for UNIX-style paths (/path/to/file), ntpath for Windows paths, macpath for old-style MacOS paths, and os2emxpath for OS/2 EMX paths.


The syntax is:

>>> import os
>>> os.path.isfile('/tmp/foobar')
>>> os.path.isfile('/tmp/foobar')


The following program check if a file exists or not:

import os
# make sure php-cgi file exists, else show an error
if ( not os.path.isfile(_php)):
    print("Error: %s file not found" % _php)
    print("Setting php jail using %s ..." % _php)

Sample outputs:

Setting php jail using /usr/bin/php-cgi ...

Another option is to check if a file exists using a try: statement:

# This is a secure method to see if a file exists and it avoids race condition too
import os
   with open(datafile) as f: print("Testing your dns servers, please wait...")
except IOError as e:
   print("Error: %s not found." % datafile)
Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?

{ 0 comments… add one }

Leave a Comment