#Write function called average_file. average_file should #have one parameter: a filename. # #The file should have an...
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 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?
Java An Introduction To Problem Solving And Programming
ISBN: 9780134462035
8th Edition
Authors: Walter Savitch