file iterator - what happens here?

Scott David Daniels scott.daniels at acm.org
Fri May 16 11:45:21 EDT 2003


Duncan Booth wrote:
> Helmut Jarausch <jarausch at skynet.be> wrote:
 >> cmd_input= file('Tree.inp','r')
 >> for line in cmd_input:
 >>      while  line.startswith('%') : # skip comment lines
 >>          print "!!!",line
 >>          line= cmd_input.readline()
 >>      print "===",line,"<<<"
 >>      if not line: break
 >> cmd_input.close()
>
 > ...For Python 2.2.x, create an explicit iterator on the file
 >> for line in cmd_input:
becomes:
 > cmd_input_iter = iter(cmd_input)
 > for line in cmd_input:
and
 >>          line= cmd_input.readline()
becomes:
 >          line= cmd_input_iter.next()

> ...For Python 2.3, you can just use the file itself:
>>          line= cmd_input.readline()
becomes:
>          line= cmd_input.next()

The easiest fix for code like this (works in all versions):

  cmd_input= open('Tree.inp','r')
  for line in cmd_input:
       if line.startswith('%') : # skip comment lines
           print "!!!",line
           continue
       print "===",line,"<<<"
       if not line: break
  cmd_input.close()

This code leaves the fetch in a single spot, and actually
obeys the comment ("skip comment lines"), rather than
attempting what the code did ("skip comment blocks").

-Scott David Daniels
Scott.Daniels at Acm.Org






More information about the Python-list mailing list