Write a python program to accept a file name from the user and perform the following operations

6. a)Write a python program to accept a file name from the user and perform the following
operations

  1. Display the first N line of the file
  2. Find the frequency of occurrence of the word accepted from the user in the file
import os.path
import sys
fname=input("Enter the filename: ")
if not os.path.isfile(fname):
    print("File",fname,"doesn't exists")
    sys.exit(0)
infile=open(fname,"r")
lineList=infile.readlines()
for i in range(5):
    print(i+1,":",lineList[i])
word=input("Enter a word:")
Cnt=0
for line in lineList:
    Cnt+=line.count(word)
print("The word",word,"appears",Cnt,"times")

Leave a Reply

Your email address will not be published. Required fields are marked *