Reading one line from the file

Sometimes we want to read only one line of the file at a time. Suppose we want to read the first line in a file called input that contains

3.523  1.254

and assign the first number to x and the second to y. Here is how we could do this:

fp = open("input"):
line = fp.readline()
xstr, ystr = line.rstrip().split()
x = float(xstr)
y = float(ystr)

The readline() method of the file object reads one line. We use the rstrip() method to remove the new-line and the split() method to separate the fields, saving the result in xstr and ystr. Note that these string methods are chained together here. We then convert the strings to floats. This step is necessary because the readline() method reads the line as a string and the split() method breaks a string into smaller strings. If we want to use the numbers in a calculation, we need to convert them to floats first.