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
Difficulty level Easy
Root privileges No
Requirements python
Est. reading time N/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)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum