End of file

Nick Craig-Wood nick at craig-wood.com
Thu Oct 7 17:29:57 CEST 2004


Duncan Booth <duncan.booth at invalid.invalid> wrote:
>  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

I like that.  I generalised it into a general purpose iterator thing.

You'll note I use the spurious sentinel local variable to mark unused
values rather than None (which is likely to appear in a general
list).  I think this technique (which I invented a few minutes ago!)
is guaranteed correct (ie sentinel can never occur in iterator).

def iterlast(iterator):
    "Returns the original sequence with a flag to say whether the item is the last one or not"
    sentinel = []
    prev, next = sentinel, sentinel
    for next in iterator:
        if prev is not sentinel:
            yield prev, False
        prev = next
    if next is not sentinel:
        yield next, True

for line, last in iterlast(file('z')):
    print last, line

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list