Python File Exists API

The operating system (os) module has a sub module by the name 'path' that contains a method isfile(). This method can be used to know whether a file that we are opening really exists or not.

For example, os.path.isfile(fname) gives True if the file exists otherwise False. We can use it as:

if os.path.isfile(fname): 
#if file exists, 
f = open(fname, 'r') 
#open it 
else: print(fname+' does not exist') 
sys.exit() #terminate the program

Example for Python File Exists API

import os, sys
fname = input('Enter filename:') 
if os.path.isfile(fname): 
   f = open(fname, 'r') 
else: 
   print(fname+' does not exist') 
   sys.exit() 

print('The file contents are:') 
str = f.read() 
print(str) 
f.close()

Python program to count number of lines, words and characters in a text file

import os, sys 
fname = input('Enter filename:') 
if os.path.isfile(fname): 
   f = open(fname, 'r') 
else: 
   print(fname+' does not exist') 
   sys.exit() 
cl= cw= cc = 0 
for line in f: 
   words = line.split() 
   cl +=1 
   cw += len(words) 
   cc += len(line) 
print('No. of lines:', cl) 
print('No. of words:', cw) 
print('No. of characters:', cc)
f.close()