'While' question

John Machin sjmachin at lexicon.net
Thu Aug 21 19:41:09 EDT 2008


On Aug 22, 9:01 am, Ben Keshet <kesh... at umbc.edu> wrote:
> Thanks for the reference.  I tried it with a general example and got it
> to work - I used an index that counts up to a threshold that is set to
> break.  It does not work though with my real code. I suspect this is
> because I cannot really read any lines from an empty file, so the code
> gets stuck even before I get to j=j+1:
>
> line = f.readline()[:-1]
>             j=0
>             while 'PRIMARY' not in line:
>                 line = f.readline()[:-1]
>                 j=j+1
>                 if j==30:
>                    break
>
> Any suggestions?
>

(1) don't top-post
(2) use a 'for' statement
(3) readline is antique
(4) don't throw away the last character in the line without knowing
what it is

for line in f:
   line = line.rstrip('\n')
   # do something useful here
   if 'PRIMARY' in line:
      break
   # do more useful stuff here

A quick rule of thumb for Python: if your code looks ugly or strained
or awkward, it's probably also wrong.

HTH,
John



More information about the Python-list mailing list