Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem #3 In Python, write a function called countLines() that takes a string r

ID: 3788104 • Letter: P

Question

Problem #3

In Python, write a function called countLines() that takes a string representing the name of a file as a parameter, and a string representing a word as the second parameter. The function should go line by line through the file and count the number of lines that contain the word. It should then return that value.

For example, if you are searching through 'example.txt' which contains the following:

Here is a random file...

This is the second line.

There is a blank line above this line.

Then  countLines('example.txt', 'is') would return 3.

countLines('example.txt','line') would return 2.

Note that the string 'line' is present once in line 2, and twice in line 4. However, we are only counting the lines that contain this string.

Hint: Look up the function 'find()' in the string class. What does it return if a string is NOT found?

Your program should use exception handling to look for either an IOError or a FileNotFoundError when the opening the input file. If the program can't open the file, print a line that says: 'Unable to open file'. Then end the function using the 'return' statement. (Do not return any value).

Explanation / Answer

def countLines(name,word):
   try:
       f = open(name,'r')
       #print("Done!!")
   except IOError:
       print("Unable to open the file")
       return
   count=0
   for l in f.readlines():
       if(l.find(word) > -1):
           count+=1
   return count

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote