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?

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)

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts