Average of Numbers
Assume that a file containing a series of integers is named numbers.txt and exists on the computer’s disk. Write a program that calculates the average of all the numbers stored in the file.
Average of Numbers Python code:
#a file containing a series of integers
#is named numbers.txt
inputFile = "numbers.txt"
#Calculates the average of all the numbers
#stored in the file.
try:
with open(inputFile, 'r') as file:
numbers = file.read().split()
total = sum(map(int, numbers))
count = len(numbers)
if count > 0:
average = total / count
print(f"The average of the numbers in '{inputFile}' is: {average}")
else:
print(f"The file '{inputFile}' is empty.")
except FileNotFoundError:
print(f"File '{inputFile}' not found.")
except IOError:
print(f"An error occurred while reading the file '{inputFile}'.")
except ValueError:
print(f"The file '{inputFile}' contains non-integer values.")
Data in "numbers.txt" file:
5
10
20
40
5
95
20
30
Executed Output:
The average of the numbers in 'numbers.txt' is: 28.125