'While' question
Larry Bates
larry.bates at vitalEsafe.com
Thu Aug 21 19:29:34 EDT 2008
Ben Keshet 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?
>
> BK
>
>
> Wojtek Walczak wrote:
>> On Thu, 21 Aug 2008 18:01:25 -0400, Ben Keshet wrote:
>>
>>> somehow. I use 'while 'word' not in line' to recognize words in the
>>> texts. Sometimes, the files are empty, so while doesn't find 'word'
>>> and runs forever. I have two questions:
>>> 1) how do I overcome this, and make the script skip the empty files?
>>> (should I use another command?)
>>> 2) how do I interrupt the code without closing Python? (I have
>>> ActivePython)
>>>
>>
>> Try the docs first. You need to read about 'continue' and
>> 'break' statements: http://docs.python.org/tut/node6.html
>>
>> HTH.
>>
>>
>
You might consider turning this around into something like:
for j, line in enumerate(f):
if 'PRIMARY' in line:
continue
if j == 30:
break
IMHO this is MUCH easier to understand.
-Larry
More information about the Python-list
mailing list