first, second, etc line of text file

George Sakkis george.sakkis at gmail.com
Wed Jul 25 16:12:30 EDT 2007


On Jul 25, 3:44 pm, "Daniel Nogradi" <nogr... at gmail.com> wrote:

> 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().

HTH,
George




More information about the Python-list mailing list