Question: #Write function called average_file. average_file should #have one parameter: a filename. # #The file should have an integer on each line. average_file #should return the

#Write function called average_file. average_file should
#have one parameter: a filename.
#
#The file should have an integer on each line. average_file
#should return the average of these integers. However, if
#any of the lines of the file are _not_ integers,
#average_file should return the string "Error reading file!"
#
#Remember, by default, every time you read a line from a
#file, it's interpreted as a string.


#Add your function here!
def average_file(filename):
   f=open(filename,"r")    
   if f.isdigit():
       numlist=[]
       for item in f:
           numlist.append(int(item))
           avg=sum(numlist)/len(numlist)
           return str(avg)
   else:
       return "Error reading file!"

   f.close()

 

#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: 5.0, then Error reading file!
#
#You can select valid_file.txt and invalid_file.txt from
#the dropdown in the top left to preview their contents.
print(average_file("valid_file.txt"))
print(average_file("invalid_file.txt"))

 

 

valid file.txt

1
2
3
4
5
6
7
8
9

 

 

invalid file.txt

1
2
3
4
5
wut
6
7
8
9

 

####

How can I fix the code to make this work? 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!