'Adding the mean average of numbers from a .txt file to my code

The code below is working completely fine, however I want to add the mean average of the inputted numbers (stored in a .txt file). Im thinking i will have to put the inputted values on different lines but im not sure how to do that either. Is there a simple way to do this?

myFile = open("C38test.txt","wt")
myFile.write(input("Enter numbers to put in a list, leave a space between each number. \n"))
myFile.close()

myFile = open("C38test.txt","rt")
contents = myFile.read()
user_list = contents.split()

for i in range(len(user_list)):
             user_list[i] = int(user_list[i])
print("Sum = ",sum(user_list))
    


Solution 1:[1]

Note: This question is very similar to this question.

The average, or mean, of a set of values is the sum of all the values divided by the number of values.

There are two main ways I have found:

Method 1: use the sum and len functions average = sum(user_list)/len(user_list), and then you can do whatever you want with the variable average of type int

Method 2: use the statistics module to do it for you

On Python 3.8+ (works with floats)

import statistics
average = statistics.fmean(user_list)

On Python 3.4+

import statistics
average = statistics.mean(user_list)

Not sure about the add-on about putting it in a file, but you can do

with open("filename.txt", "w") as fout:
    fout.write(str(average))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kenntnisse