How do I print lines from a file in python after and before a match?

Question:

I would like to print some specific lines from a file, only those lines that come after a certain word appears on a line (‘Ingredients:’) and before another word appears (‘Instructions:’).
The file is a list of recipes and I want to be able to print out only the ingredients.

example of the text:

RECIPE : CACIO E PEPE #PASTA
Ingredients:
spaghetti: 200-g
butter: 25-gr
black pepper: as needed
pecorino: 50-gr
Instructions:

I tried this way and many others but nothing seems to work:

def find_line_after(target):
    with open('recipes.txt', 'r') as f:
        line = f.readline().strip()
        while line:
            if line == target:
                line = f.readline().strip()
                return f.readline()
            
Asked By: Tommaso Maganzani

||

Answers:

This may help you:

start, stop = 0, 0
with open('recipes.txt', 'r') as f:
    lines = f.readlines()
for n in range(len(lines)):
    if 'Ingredients' in lines[n]:
        start = n + 1
    elif 'Instructions' in lines[n]:
        stop = n
ingredients = list(filter(('n').__ne__, lines[start:stop]))
for i in ingredients:
    print(i, end='')

Basically looks for the start and stop indexes, fetches the lines from that range and removes the empty lines (and extra new-line chars).

Output:

spaghetti: 200-g
butter: 25-gr
black pepper: as needed
pecorino: 50-gr
Answered By: CreepyRaccoon
def get_all_ingredients():
    flag = False
    with open('recipes.txt', 'r') as f:
        for line in f:
            if 'Instructions' in line:
                flag = False

            if flag:
                print(line.rstrip())

            if 'Ingredients' in line:
                flag = True


get_all_ingredients()

Tested input:

RECIPE : CACIO E PEPE #PASTA
Ingredients:
spaghetti: 200-g
butter: 25-gr
black pepper: as needed
pecorino: 50-gr
Instructions:
asd
RECIPE : CACIO E PEPE #PASTA
Ingredients:
salt: 200-g
chicken: 25-gr
Instructions:
qwe
qwe
RECIPE : CACIO E PEPE #PASTA
Ingredients:
carrot: 200-g
rabbit: 25-gr
Instructions:
qwe
qwe

Output got:

spaghetti: 200-g
butter: 25-gr
black pepper: as needed
pecorino: 50-gr
salt: 200-g
chicken: 25-gr
carrot: 200-g
rabbit: 25-gr
Answered By: NahuelBrandan

My approach involves setting a variable is_ingredient to True or False, depending on the line and print if it is True.

is_ingredient = False
with open("recipes.txt", "r", encoding="utf-8") as stream:
    for line in stream:
        if line.startswith("Ingredients:"):
            is_ingredient = True
        elif line.startswith("Instructions:"):
            is_ingredient = False
            print("---")
        elif is_ingredient:
            print(line, end="")

The only addition I did was to print the --- as a separator between recipes.

Answered By: Hai Vu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.