I have a huge text file consisting of "blocks" like this:
block
object pen
fruit apple
people mike
block
electronic laptop
city dallas
fruit banana
object stapler
vehicle car
block
people george
fruit orange
vehicle truck
city austin
object hammer
In each block there is only one fruit at a random line. Each block has different number of lines. I want to iterate in this file, print everything including the fruit's name, and then skip until the next block. Once I find the fruit in one block, it is a waste of time to check if the next line is fruit or not. I just want to jump to the next block, but the problem is I don't know how many lines ahead the block is. So the output should look like:
block
object pen
the fruit is: apple
block
electronic laptop
city dallas
the fruit is: banana
block
people george
the fruit is: orange
I can produce this output in two ways, one:
flag = True
with open("sample.txt", "r") as f:
for line in f.readlines():
if line.split()[0] == 'fruit':
print "the fruit is: " + line.split()[1]
flag = False
if line.split()[0] == 'block':
flag = True
if flag:
print line
And two:
flag = False
with open("sample.txt", "r") as f:
for line in f.readlines():
if line.split()[0] == 'fruit':
print "the fruit is: " + line.split()[1]
flag = True
if line.split()[0] == 'block':
flag = False
if flag:
continue
print line
But this is not what I want. My code still checks each line whether it is fruit. I want to skip the lines after fruit until block, and continue from there. How can I do that jump?
if flag and line.split()[0] == 'fruit':just test for the flag to avoid comparison