read a files particular line

Alex Martelli aleaxit at yahoo.com
Fri Oct 15 03:04:53 EDT 2004


Frank Grellert <fgrellert at t-online.de> wrote:

> does anybody have an idea how to read a particular line of a file like awk's
> awk '{if( NR==12) print $0}' filename (reads lineno 12 of filename)

Standard Python library module linecache, which others suggested, is
your best bet.  itertools.islice(open('filename'), 12, 13).next() should
also work (after an 'import itertools' of course, since it, too, is a
module in the standard library) and might be faster if you'll never need
to get any other line from that file in the course of your program.


Alex



More information about the Python-list mailing list