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

Posted on in Categories last updated November 18, 2012

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


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.

Syntax

The syntax is:

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

Examples

The following program check if a file exists or not:

#!/usr/bin/python
import os
_php="/usr/bin/php-cgi"
 
# make sure php-cgi file exists, else show an error
if ( not os.path.isfile(_php)):
    print("Error: %s file not found" % _php)
else:
    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:

#!/usr/bin/python
# This is a secure method to see if a file exists and it avoids race condition too
import os
datafile="/etc/resolv.conf"
try:
   with open(datafile) as f: print("Testing your dns servers, please wait...")
except IOError as e:
   print("Error: %s not found." % datafile)
Reference:

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Leave a Comment