use fileinput to read a specific line

Russ P. Russ.Paielli at gmail.com
Tue Jan 8 01:16:56 EST 2008


On Jan 7, 9:41 pm, Dennis Lee Bieber <wlfr... at ix.netcom.com> wrote:
> On Mon, 7 Jan 2008 20:10:58 -0800 (PST), "Russ P."
> <Russ.Paie... at gmail.com> declaimed the following in comp.lang.python:
>
> > for file0 in files:
>
> >     lnum = 0 # line number
>
> >     for line in file(file0):
> >         lnum += 1
> >         if lnum >= 4: break
>
> >     # do something with "line"
>
> > where "files" is a list of the files to be read.
>
>         Given that the OP is talking 2000 files to be processed, I think I'd
> recommend explicit open() and close() calls to avoid having lots of I/O
> structures floating around...
>
> for fid in file_list:
>         fin = open(fid)
>         jnk = fin.readline()
>         jnk = fin.readline()
>         jnk = fin.readline()
>         ln = fin.readline()
>         fin.close()
>
>         Yes, coding three junk reads does mean maintenance will be a pain
> (we now need the 5th line, not the fourth -- and would need to add
> another jnk = line)... I'd maybe consider replacing all four readline()
> with:
>
>         for cnt in xrange(4):
>                 ln = fin.readline()
>
> since it doesn't need the overhead of a separate line counter/test and
> will leave the fourth input line in "ln" on exit.
> --
>         Wulfraed        Dennis Lee Bieber               KD6MOG
>         wlfr... at ix.netcom.com              wulfr... at bestiaria.com
>                 HTTP://wlfraed.home.netcom.com/
>         (Bestiaria Support Staff:               web-a... at bestiaria.com)
>                 HTTP://www.bestiaria.com/

One second thought, I wonder if the reference counting mechanism would
be "smart" enough to automatically close the previous file on each
iteration of the outer loop. If so, the files don't need to be
explicitly closed.



More information about the Python-list mailing list