In Python Implement a function averagePerLine that takes one

In Python, Implement a function averagePerLine() that takes one parameter which is a string representing the name of a text file.

The function should return the average number of characters of all the lines in the file.

For example, if the first line had 20 characters, the second line had 30 characters, and the last line had 40 characters, then the function should return 40 ie: (30+40+50) /  40.  

If the file is empty, the function should return 0.

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

The following shows what the function would return when called on example.txt and on a non-existing file called \'none.txt\':

print( averagePerLine(\'example.txt\') )

#would output 22.25

(The first line has 25, second line has 25, third line has 1 – because of the \'\ \' character), and fourth line has 38. So (25+25+1+38)/4 = 22.25.

print( averagePerLine(\'none.txt\') )

#would output: \"Unable to open file.\"

Solution

CODE:

def averagePerLine(fileName):
   # declare variables here.
   sum = lines = 0

   # execute rest of the code in try catch block.
   try:
       # open the file in read mode.
       # Give the input file name here.
       with open(fileName, \'r\') as in_file:
           # for every line of the file.
           for line in in_file:
               # increment the line count.
               lines += 1
               # convert the line to list and remove blank characters and the newline.
               line = list(line)
              
               while \' \' in line:
                   line.remove(\' \')
                  
               if \'\ \' in line:
                   line.remove(\'\ \')
              
               # sum up the number of characters in single line.
               sum += len(line)  
              
       # calculate the average.
       avg = sum/lines
      
       return avg

   # if the file name is not given
   except (FileNotFoundError, IOError) as e:
       print \"File not found !!\"
       print e

print averagePerLine(\'example.txt\')

example.txt
t h i s
s s d f g
s d qw ewe

OUTPUT:
$python test.py
5

In Python, Implement a function averagePerLine() that takes one parameter which is a string representing the name of a text file. The function should return the
In Python, Implement a function averagePerLine() that takes one parameter which is a string representing the name of a text file. The function should return the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site