read a files particular line

F

Frank Grellert

Hi,
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)

thanks for your help

Frank Grellert
 
?

=?ISO-8859-1?Q?Krist=F3f_Str=F3bl?=

Hi,

If the file is not too big use:

file("filename").readlines()[11]

Kristóf
 
P

Peter L Hansen

Kristóf Stróbl wrote (top-posting, but I fixed it. You're welcome.):
>> 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)
>
If the file is not too big use:

file("filename").readlines()[11]

And if the file is "too big", there's always iterators:

print itertools.islice(open('tempx.txt'), 11, 12).next()

A little more complicated, but avoids reading the entire file
into memory.

-Peter
 
M

Miki Tebeka

Hello Frank,
Hi,
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)
Check the documentation about the "linecache".

HTH.
 
M

Michael Hudson

Frank Grellert said:
Hi,
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)

for lineno, line in enumerate(open_file):
# lineno starts at 0, though

Cheers,
mwh
 
A

Alex Martelli

Frank Grellert said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,209
Messages
2,571,088
Members
47,686
Latest member
scamivo

Latest Threads

Top