Search code examples
pythonloopsreadfile

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


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()
            

Solution

  • 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