How to Check a Particular File Exists or Not?

0


How to Check a Particular File Exists or Not?

  • We can use os library to get information about files in our computer. os module has path sub module,which contains isFile() function to check whether a particular file exists or not? 

Syntax

  • os.path.isfile(file name) 

Q. Write a program to check whether the given file exists or not. If it is available then print its content? 

Source Code: 

#Follow - Programmerfect


import os,sys

fname=input("Enter File Name: ")

if os.path.isfile(fname):

    print("File exists:",fname)

    f=open(fname,"r")

else:

    print("File does not exist:",fname)

    sys.exit(0)

print("The content of file is:")

data=f.read()

print(data)  

Output:

Note: 

  • sys.exit(0) ===>To exit system without executing rest of the program. 
  • argument represents status code . 0 means normal termination and it is the default value.

Q. Program to print the number of lines,words and characters present in the given file?

Source Code:

#Follow - Programmerfect

import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
    print("File exists:",fname)
    f=open(fname,"r")
else:
    print("File does not exist:",fname)
    sys.exit(0)
lcount=wcount=ccount=0
for line in f:
    lcount=lcount+1
    ccount=ccount+len(line)
    words=line.split()
    wcount=wcount+len(words)
print("The number of Lines:",lcount)
print("The number of Words:",wcount)
print("The number of Characters:",ccount) 

Output:

 


 

 

Post a Comment

0Comments
Post a Comment (0)