Python isfile() method

The operating system (os) module has a sub module by the name 'path' that contains a method isfile() .

isfile() method

isfile() 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:

CopiedCopy Code
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

isfile() examples

example 1:
CopiedCopy Code

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()
example 2:
CopiedCopy Code

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()