End of file

Duncan Booth duncan.booth at invalid.invalid
Thu Oct 7 04:36:43 EDT 2004


Kat wrote:

> 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.
> 

You need to read the next line before you can tell which is the last line. 
The easiest way is probably to use a generator:

def lineswithlast(filename):
    prev, line = None, None
    for line in file(filename):
        if prev is not None:
            yield prev, False
        prev = line
    if line:
        yield line, True

	
for line, last in lineswithlast('somefile.txt'):
    print last, line



More information about the Python-list mailing list