first, second, etc line of text file

James Stroud jstroud at mbi.ucla.edu
Wed Jul 25 18:14:28 EDT 2007


Daniel Nogradi 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?

This is the same logic but less cumbersome, if that's what you mean:

to_get = [0, 3, 7, 11, 13]
got = dict((i,s) for (i,s) in enumerate(open(textfile)) if i in to_get)
print got[3]

This would probably be the best way for really big files and if you know 
all of the lines you want ahead of time. If you need to access the file 
multiple times at arbitrary positions, you may need to seek(0), cache 
lines already read, or slurp the whole thing, which has already been 
suggested.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list