first, second, etc line of text file

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Jul 26 03:56:53 CEST 2007


En Wed, 25 Jul 2007 19:14:28 -0300, James Stroud <jstroud at mbi.ucla.edu>  
escribió:

> 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:
>
> 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.

But it still has to read the complete file (altough it does not keep the  
unwanted lines).
Combining this with Paul Rubin's suggestion of itertools.islice I think we  
get the best solution:
got = dict((i,s) for (i,s) in  
enumerate(islice(open(textfile),max(to_get)+1)) if i in to_get)

-- 
Gabriel Genellina




More information about the Python-list mailing list