first, second, etc line of text file

Daniel Nogradi nogradi at gmail.com
Thu Jul 26 08:46:02 EDT 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?
>
> If all you need is sequential access, you can use the next() method of
> the file object:
>
> nextline = open(textfile).next
> print 'First line is: %r' % nextline()
> print 'Second line is: %r' % nextline()
> ...
>
> For random access, the easiest way is to slurp all the file in a list
> using file.readlines().

Thanks! This looks the best, I only need the first couple of lines
sequentially so don't need to read in the whole file ever.



More information about the Python-list mailing list