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:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop











{ 0 comments… add one now }