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

by on November 18, 2011 · 0 comments· LAST UPDATED November 18, 2012

in

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

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Requirementspython
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.

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:
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: , , , , ,

Previous Faq:

Next Faq: