Вы используете str.find (sub [, start [, end]]) и задаете значение start
после последнего найденного ']'
для нового поиска - поместите его на некоторое время l oop до тех пор, пока не будет найдено больше '['
:
file = "t.txt"
with open(file,"w") as f:
f.write("""nothing
some [one] some
some [one] some [two] more [three] things
some [one] some""")
try:
with open(file) as f:
for idx, line in enumerate(f,1):
line = line.rstrip()
pos = line.find('[') # store first position
while pos != -1: # only continue if found
atpos2 = line.find(']', pos) # find end after pos
info = line[pos+1:atpos2] # get part
pos = line.find('[',atpos2) # find next start after end
print(f"Found '{info}' in line {idx}")
except Exception as e: # maybe print the error as well...
print('stop being a stupid', e)
print('you are done')
Вывод:
Found 'one' in line 2
Found 'one' in line 3
Found 'two' in line 3
Found 'three' in line 3
Found 'one' in line 4
you are done
Часть atpos2 = line.find(']', pos) # find end after pos
важна для строки типа
'this ] will give you [weird] outputs [ elsewise'