144k views
25 votes
Write a function named average_value_in_file that accepts a file name as a parameter and reads that file, assumed to be full of numbers, and returns the average (mean) of the numbers in that file. The parameter, filename, gives the name of a file that contains a list of numbers, one per line. You may assume that the file exists and follows the proper format. For example, if a file named input.txt contains the following numbers

User Slouc
by
5.6k points

1 Answer

3 votes

def average_value_in_file(filename):

f = open(filename)

total = 0

count = 0

for x in f.read().splitlines():

total += int(x)

count += 1

return total/count

print(average_value_in_file("input.txt"))

I used an input file that looks like this:

1

1

1

1

User Grekker
by
5.5k points