Friday, July 13, 2012

Python: Check for file existence

Current post is on how to check whether file exists on system running Python 3.2.


First import the 'os.path' module.  os.path module implements some useful functions on pathname.

import os.path

Add the following line to check file.
  
os.path.exists(filename)

It returns True if filename exists else returns False


To make sure it is file and it exists, one can use:

os.path.isfile(filename)

It returns True only if the type is of file and it exists else returns False


Example 1: File Check using 'exists' function

      if os.path.exists("HelloWorld.py"):
           print("Hello World")
      else:
           print("No World !!!")

Example 2: File Check using 'isfile' function

      if os.path.isfile("HelloWorld.py"):
           print("Hello World")
      else:
           print("No World !!!")


No comments:

Post a Comment

Disclaimer:

The above post and all the posts in the blog are derived from facts, information, logical interpretation and logical conclusion of printed and internet materials available to me, perceived and produced by 99 gm brain of mine, which by no means always be accurate, consistent and complete.

All the posts are for personal quick reference only.

If any suggestion, correction, misinterpretation, misconception commented, which will be moderated and deleted if required, to avoid unforeseen issues.

If any trademark / copywrite issue is present, do send in a mail and appropriate tag (logo, name, website link) will be attached to the same.

Additional disclaimer will be attached wherever required in the post.