Write a function called countlines that takes a string


Problem

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

Request for Solution File

Ask an Expert for Answer!!
Computer Engineering: Write a function called countlines that takes a string
Reference No:- TGS02897440

Expected delivery within 24 Hours