first, second, etc line of text file

Daniel Nogradi nogradi at
Wed Jul 25 21:44:39 CEST 2007

A very simple question: I currently use a cumbersome-looking way of
getting the first, second, etc. line of a text file:

for i, line in enumerate( open( textfile ) ):
    if i == 0:
        print 'First line is: ' + line
    elif i == 1:
        print 'Second line is: ' + line

I thought about f = open( textfile ) and then f[0], f[1], etc but that
throws a TypeError: 'file' object is unsubscriptable.

Is there a simpler way?

More information about the Python-list mailing list