Final answer:
To find the average of numbers in a file using Python, open the file, use a for loop to read and sum the numbers, count the total entries, and then divide the sum by the count. Print the result with two decimal places.
Step-by-step explanation:
To calculate the average of numbers in a file using Python, you need to open the file, read the numbers, and perform calculations accordingly. Here is an example of how you can achieve this within the main function:
def main():
total_sum = 0
count = 0
with open('my_file.txt', 'r') as file:
for line in file:
try:
number = float(line)
total_sum += number
count += 1
except ValueError:
# Handle the exception if the line is not a number
print(f'Unable to convert {line} to a number. Skipping...')
if count > 0:
average = total_sum / count
print(f'The average is {average:.2f}')
else:
print('No numbers found in the file.')
if __name__ == '__main__':
main()
This code snippet includes the whole process: opening the file, reading numbers, calculating the average, and closing the file implicitly by using the with statement. The average is printed with two decimal places as requested.