End of file

Alex Martelli aleaxit at yahoo.com
Thu Oct 7 13:38:43 CEST 2004


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.


Alex



More information about the Python-list mailing list