I'm looking to have the program read a text file that is formatted like this for example.
Kristen
100
Maria
75
Frank
23
Is there anyway in python to skip lines and have it read only the numbers, accumulate them, and average them out? Could be more numbers or less numbers than the example above. I'm very much stuck.
CodePudding user response:
you can use re.findall to find all numbers in a string:
import re
if __name__ == "__main__":
numbers = []
with open("./file.txt", "r") as f:
for line in f:
line = line.strip()
temp = list(map(lambda x: eval(x), re.findall(r'\d ', line)))
numbers = temp
average = sum(numbers) / len(numbers)
print(average)
CodePudding user response:
This is the method I would use:
def get_average(filepath):
total = 0.0
with open(filepath, 'r') as f:
lines = f.readlines()
numbers = 0
for line in lines:
try:
number = int(line.strip())
total = number
numbers = 1
except:
continue
return total / float(numbers)
get_average("path/to/file.txt")
CodePudding user response:
use strip
to get rid of newline and isdigit
to check for digit
In [8]: with open('a.txt', 'r') as f:
...: s = [int(i.strip()) for i in f if i.strip().isdigit()]
...:
In [9]: sum(s)/len(s)
Out[9]: 66.0
CodePudding user response:
# assuming a score always follows a players name.
with open("path_to_file.ext", "r") as inf:
print(inf.readlines()[1::2]) # Do something with the result
# only grabbing lines that can be interpreted as numbers
with open("path_to_file.ext", "r") as inf:
for _ in inf.readlines():
if _.rstrip().isnumeric():
print(_.rstrip()) # Do something with the result
CodePudding user response:
If the file name 'file.txt'
total = 0
i = 0
with open('file.txt', 'r') as file:
for line in file:
try:
total = int(line)
i = 1
except:
continue
average = total / i