while loop with f.readline()

Steve Purcell stephen_purcell at yahoo.com
Tue Feb 13 18:39:18 CET 2001


Chris Richard Adams wrote:
> I'm trying to create a loop that reads through a simple file with
> strings on each line.
> 
> f=open('/tmp/xferlog', 'r')
> while f.readline():
>  line = f.readline()
>  print line


In the code above, the line returned from 'f.readline()' in the 'while'
condition is simply thrown away, so only every second line is printed.

You probably mean:

  while 1:
    line = f.readline()
    if not line: break
    print line

It may look a bit strange, but it's a Python idiom and is the best way to
do this kind of input loop.

> f=open('/tmp/xferlog', 'r')
> while f.readline():
>  line = f.readline()
>  print line
>  f.close()
> 
> How do i code the loop to know that it should be executed after the
> loop...not after each iteration???

Put the 'close' call in the appropriate block -- the blocks are contiguous
areas of equal indentation. You don't want the 'close' call in the block
internal to the loop, or it will be executed each time through the loop.

You want:

  while 1:
    line = f.readline()
    if not line: break
    print line
  f.close()


-Steve

-- 
Steve Purcell, Pythangelist
http://pyunit.sourceforge.net/
http://pyserv.sourceforge.net/
Available for consulting and training.
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list