python read line from file or user input code example
Example 1: python reading into a text file and diplaying items in a user friendly manner
def extract_data(filename):
infile = open(filename, 'r')
infile.readline()
data = [line.split() for line in infile]
annual_avg = data[-1][1]
data = [(m, float(r)) for m, r in data[:-1]]
infile.close()
return data, annual_avg
Example 2: python reading into a text file and diplaying items in a user friendly manner
def extract_data(filename):
infile = open(filename, 'r')
infile.readline()
months = []
rainfall = []
for line in infile:
words = line.split()
months.append(words[0])
rainfall.append(float(words[1]))
infile.close()
months = months[:-1]
annual_avg = rainfall[-1]
rainfall = rainfall[:-1]
return months, rainfall, annual_avg
months, values, avg = extract_data('rainfall.dat')
print 'The average rainfall for the months:'
for month, value in zip(months, values):
print month, value
print 'The average rainfall for the year:', avg