Reputation: 1
for line in open(fname, 'r'):
if re.search('#', line):
#print(line)
pass
elif re.search('# segment: retract', line):
print(line)
print('break here')
break
else:
outfile.write(line)
The elif statement does not work, can anybody help me with a regexp that matches
"# segment: retract"
the code does not even enter the elif statement.
Thanks
Upvotes: 0
Views: 101
Reputation:
The first expression of the if clause will always match for lines containing '#'. So your more specific condition in the elif clause will never match since the more generic condition in the if clause is always executed. So you would test the more specific conditions first and move the more generic condition(s) into the elif part.
for line in open(fname, 'r'):
if re.search('# segment: retract', line):
print(line)
print('break here')
break
elif re.search('#', line):
#print(line)
pass
else:
outfile.write(line)
Upvotes: 3
Reputation: 9590
I don't think this is regex is the prob. The condition needs to be reversed like
if re.search('# segment: retract', line):
print(line)
print('break here')
break
elif re.search('#', line):
#print(line)
pass
else:
outfile.write(line)
The problem is the first if condition catching all lines starting with #
and else never happens.
Upvotes: 3