<p>考虑一下</p>
<pre><code>fname = 'crispr_pilrcr_1.out'
counter = 0
printing = False
for line in open(fname, 'r'): # Open up the file
s = line.split() # Split each line into words
if not s: continue # Remove empty lines which would otherwise cause errors
if '==' in s[0]: continue # Removes seperation lines which consist of long '=======' strings
try:
if s[0] == 'DETAIL': # Only start in the section which starts with 'DETAIL'
printing = True
print 'Starting'
elif s[0] == 'SUMMARY': # Only end once this section has ended
printing = False
print 'Ending'
elif printing:
try:
# Anything you put here will only be called for the lines
# between DETAIL... and SUMMARY...
except ValueError:
continue
except ValueError:
continue
</code></pre>
<p>基本上,您使用的是一个变量<code>printing</code>,它被初始化为False,当for循环遇到“DETAIL…”时设置为True,当for循环遇到“SUMMARY…”时重置为False。你知道吗</p>
<p>对于与“DETAIL…”或“SUMMARY…”不匹配的行,如果<code>printing</code>为真(即对于两个标题之间的行),将执行<code>try</code>块。你知道吗</p>