54
168
4 User input and error handling
The complete code, wrapped in a function, may look like this (file
rainfall1.py):
def extract_data(filename):
infile = open(filename, ’r’)
infile.readline() # skip the first line
months = []
rainfall = []
for line in infile:
words = line.split()
# words[0]: month, words[1]: rainfall
months.append(words[0])
rainfall.append(float(words[1]))
infile.close()
months = months[:-1]
# Drop the "Year" entry
annual_avg = rainfall[-1] # Store the annual average
rainfall = rainfall[:-1] # Redefine to contain monthly data
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
Note that the first line in the file is just a comment line and of no interest
to us. We therefore read this line byinfile.readline() and do not
store the content in any object. Thefor loop over the lines in the file
will then start from the next (second) line.
We store all the data into 13 elements in themonths andrainfall
lists. Thereafter, we manipulate these lists a bit since we wantmonths to
contain the name of the 12 months only. Therainfall list should corre-
spond to thismonth list. The annual average is taken out ofrainfall
and stored in a separate variable. Recall that the-1 index corresponds
to the last element of a list, and the slice:-1 picks out all elements from
the start up to, but not including, the last element.
We could, alternatively, have written a shorter code where the name
of the months and the rainfall numbers are stored in a nested list:
def extract_data(filename):
infile = open(filename, ’r’)
infile.readline() # skip the first line
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
This is more advanced code, but understanding what is going on is a good
test on the understanding of nested lists indexing and list comprehensions.
An executable program is found in the file rainfall2.py.
Is it more to file reading? ? Withtheexamplecodeinthissection,you
have the very basic tools for reading files with a simple structure: columns
of text or numbers. Many files used in scientific computations have such
aformat, but many files are more complicated too. Then you need the
techniques of string processing. This is explained in detail in Chapter 6.