read_ex2.py 632 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/usr/bin/env python3

f = open("example.dat")

totals = [0, 0]
count = 0
for line in f:
    count += 1
    # Each line is read as a string.
    # split() is a string method that outputs each space-separated item.
    for ii, val in enumerate(line.split()):
        # Remember we need to convert the value from a string to a number
        # before we can add it.
        totals[ii] += float(val)
# We can close the file as soon as we don't need it any more.
f.close()

for ii, total in enumerate(totals):
    # Recall python list indices start from 0, so we add 1 here.
    print("The average of column", ii+1, "is", total/count)