Checking for an end of file with readline()

The readline() method doesn't trigger the end-of-file condition. Instead, when data is exhausted, it returns an empty string.

fp = open("input")
while True:
     nstr = fp.readline()
     if len(nstr) == 0:
     n = int(nstr.rstrip())
     [do stuff using n]
[do stuff with the full dataset]

Notice that we must also remove the new-line character and convert the string to an integer. The conversion could fail if it isn't an integer. So we can catch the error:

import sys
         n = int(nstr.rstrip())
     except ValueError:
         sys.stderr.write("Can't convert " + nstr + " to int\n")

See above for a discussion of error handling with try -- except. Writing to the standard error stream is discussed below.