I am trying to get the average of a group of numbers in a .txt file. It worked when numbers are like this: every number on a separate line
363
186
262
247
:
but my .txt file is like this:
237, 321, 212, 379, 201, 247, 201, 204, 298, 130
285, 229, 167, 235, 353, 176, 130, 274, 337, 192
......
note: 1000 numbers. How to fix this?
This is what I tried:
import os
def averg_int(path):
lst = []
with open(path, "r") as file:
for line in file: # Read one line at the time
n = int(line.strip()) # Strip and convert to integer
lst.append(n)
avg=sum(lst)/len(last)
return avg
CodePudding user response:
The problem is with n = int(line.strip())
part, because you have multiple numbers in a single line, you need to split
them and then type cast to int
:
n = [int(i.strip()) for i in line.split()]