im trying to write a function in python, that reads a file, extracts the numbers after a colon in the file, and returns the average of the numbers
(simple formula for average => sum of numbers / amount of numbers)
the file looks like:
thenumber1:7
#more could be added
thenumber2: 4 (#yes there is a space after the colon)
lines that start with "#" should be ignored.
my code so far:
import os
def get_average_n(path):
s = ""
t = 0
v = 0
if not os.path.exists(path):
return None
if os.stat(path).st_size == 0:
return 0.0
else:
p = open(path, "r")
content = p.readlines()
for line in content:
if line.startswith("#"):
continue
elif not line.startswith("#"):
x = line.find(":")
s += line[x + 1:]
h = s.replace("\n", "")
for c in h:
if c.isdigit():
t += float(c)
v += 1
avg = round(t / v, 2)
return avg
print(get_average_n("file.txt"))
The output should be 5.5 in the case mentionet (fat) but im getting wrong outputs , and i really cant find the issue. It gives 6.25 back instead of 5.5.