Reputation: 125
I have a for loop iterating through my file, and based on a condition, I want to be able to read the next line in the file.I want to detect a keyword of [FOR_EACH_NAME]
once I find it, I know that names will follow and I print each name. Basically Once I find the [FOR_EACH_NAME]
keyword how can I keep going through the lines.
Python code:
file=open("file.txt","r")
for line in file:
if "[FOR_EACH_NAME]" in line
for x in range(0,5)
if "Name" in line:
print(line)
Hi everyone, thank you for the answers. I have posted the questions with much more detial of what I'm actually doing here How to keep track of lines in a file python.
Upvotes: 0
Views: 2315
Reputation: 1363
I think this will do what you want. This will read the next 5 lines and not the next 5 names. If you want the next five names then indent once the line ct+=1
#Open the file
ffile=open('testfile','r')
#Initialize
flg=False
ct=0
#Start iterating
for line in ffile:
if "[FOR_EACH_NAME]" in line:
flg=True
ct=0
if "Name" in line and flg and ct<5:
print(line)
ct+=1
Upvotes: 0
Reputation: 146
Are the names in the lines following FOR_EACH_NAME? if so, you can check what to look for in an extra variable:
file=open("file.txt","r")
names = 0
for line in file:
if "[FOR_EACH_NAME]" in line
names = 5
elif names > 0:
if "Name" in line:
print(line)
names -= 1
Upvotes: 0
Reputation: 34272
Once you found the tag, just break from the loop and start reading names, it will continue reading from the position where you interrupted:
for line in file:
if '[FOR_EACH_NAME]' in line:
break
else:
raise Exception('Did not find names') # could not resist using for-else
for _ in range(5):
line = file.readline()
if 'Name' in line:
print(line)
Upvotes: 2