Reputation: 37
I'm creating a function that reads a .txt
file that contains the following:
Testing.txt:
a 1 34
b 2 25
c 3 23
j 4 80
I need to create a function that reads this file and prints the average of the last 2 digits of each line in the file.
What I have so far is this:
def Stats():
filename = input("Enter a file name: ")
with open(filename) as f:
data = [int(line) for line in f]
print("The average value is ", sum(data)/len(data))
Stats()
Pros:
cons:
Question: How can I get my function to work with a file such as the one listed above called (testing.txt)?
Upvotes: 0
Views: 89
Reputation: 12903
Something like this:
data = [sum(map(int, line.split(' ')[1:])) / 2 for line in f]
Or something more old-school, in case you have unknown mix of string and int values:
data = []
for line in f:
integers = []
for segment in line.split():
try:
integers.append(int(segment))
except ValueError:
pass
data.append(sum(integers) / len(integers))
Upvotes: 1
Reputation: 30210
What about something like:
import csv
def mean(lst): return sum(lst) / len(lst)
with open('input.txt') as f:
reader = csv.reader(f, delimiter=' ')
lines = [line for line in reader]
col3 = [int(line[2]) for line in lines]
print(mean(col3)) # 40.5
This just uses the csv module to parse the file lines into rows containing elements. You could accomplish the same thing with something like:
def mean(lst): return sum(lst) / float(len(lst))
with open('input.txt') as f:
lines = [line.split() for line in f]
col3 = [int(line[2]) for line in lines]
print mean(col3) # 40.5
Upvotes: 1
Reputation: 9753
You could ignore non-numbers this way:
data = [int(token) for token in f.read().split() if token.isdigit()]
Upvotes: 1
Reputation: 238111
I think this is what you are after:
# filename = input("Enter a file name: ")
filename = "input.txt"
def avg_file(filename):
with open(filename, 'r') as f:
data = [int(line.split()[2]) for line in f]
return sum(data)/len(data)
avg = avg_file(filename)
print("The average value is: ", avg)
# The average value is: 40.5
the key is this line.split()[2]
. This splits a line based on spaces, and takes 3th value.
Upvotes: 1