Reading numbers from a file

To read in the numbers from the file powers.txt generated in the previous example, the columns must be converted to lists of integers. To do this, each line must be split into its fields and each field explicitly converted to an int:

f = open('powers.txt', 'r')
squares, cubes, fourths = [], [], []
for line in f.readlines():
    fields = line.split(',')
    squares.append(int(fields[1]))
    cubes.append(int(fields[2]))
    fourths.append(int(fields[3]))
f.close()
n = 500
print(n, 'cubed is', cubes[n-1])

The output is:

500 cubed is 125000000

In practice, it is better to use NumPy (see Chapter 6 of the book) to read in data files such as these.