End of file

Andreas Kostyrka andreas at kostyrka.org
Thu Oct 7 14:30:03 CEST 2004


On Thu, Oct 07, 2004 at 01:38:43PM +0200, Alex Martelli wrote:
> duikboot <"adijkstra at baanders NOSPAM consultancy.nl"> wrote:
> 
> > Kat wrote:
> > > Hi ,
> > > How do you identify the last line of a file? I am in a "for" loop and
> > > need to know which is the last line of the file while it is being read
> > > in this loop.
> > > 
> > > Thanks
> > > Kat
> > 
> > f = open("test.txt").readlines()
> > lines = len(f)
> > print lines
> > counter = 1
> > for line in f:
> >      if counter == lines:
> >          print "last line: %s" % line
> >      counter += 1
> 
> A slight variation on this idea is using the enumerate built-in rather
> than maintaining the counter by hand.  enumerate counts from 0, so:
> 
> for counter, line in enumerate(f):
>     if counter == lines-1: is_last_line(line)
>     else: is_ordinary_line(line)
> 
> If the file's possibly too big to read comfortably in memory, of course,
> other suggestions based on generators &c are preferable.
This should do it "right":

f = file("/etc/passwd")
fi = iter(f)

def inext(i):
    try:
        return i.next()
    except StopIteration:
        return StopIteration

next = inext(fi)
while next <> StopIteration:
    line = next
    next = inext(fi)
    if next == StopIteration:
        print "LAST USER", line.rstrip()
    else:
        print "NOT LAST", line.rstrip()



More information about the Python-list mailing list