Hey I am a newbie at python and I need some help. I’ve written down the following code:
try:
it = iter(cmLines)
line=it.next()
while (line):
if ("INFERNAL1/a" in line) or ("HMMER3/f" in line) :
title = line
line = it.next()
if word2(line) in namesList: //if second word in line is in list
output.write(title)
output.write(line)
line = it.next()
while ("//" not in line):
output.write(line)
line = it.next()
output.write(line)
line = it.next()
except Exception as e:
print "Loop exited becuase:"
print type(e)
print "at " + line
finally:
output.close()
-
When the loop ends it always throws an Exception that notifies that the loop stopped. Even though it didn’t terminate prematurely. How do I stop that?
-
Is there a better way to write my code? Something more stylish. I have a big file that has lots of information and I am trying to catch only the information I need. Every slice of information is of the format:
Infernal1/a ... Name someSpecificName ... ... ... ... //
Thank you
RocketDonkey’s answer is spot-on. Because of the complexity of the way you’re iterating, there is no simple way to do this with a
forloop, so you’re going to need to explicitly handleStopIteration.However, if you rethink the problem a bit, there are other ways around this. For example, a trivial state machine:
Alternatively, you can write a generator function that delegates to sub-generators (via
yield from foo()if you’re in 3.3, viafor x in foo(): yield xif not), or various other possibilities, especially if you rethink your problem at a higher level.That may not be what you want to do here, but it’s usually worth at least thinking about “Can I turn this
whileloop and two explicitnextcalls into aforloop?”, even if the answer turns out to be “No, not without making things less readable.”As a side note, you can probably simplify things by replacing the
try/finallywith awithstatement. Instead of this:You can just do this:
Or, if
outputisn’t a normal file, you can still replace the last four lines with: