Preplp
Daily Python
Day 15Python~45 min

Read files & parse data

Load structured text from disk

Track progress0/15 days
x

What you'll learn

readlinessplit blocksparseFileNotFoundError
  • Read multi-line files and parse sections
  • Build a recipe viewer from a text file

Lesson & examples

Read the code, then the explanation — try changing values before the project.

Read line by line
with open("sample.txt", "r") as f:
    for line in f:
        print(line.strip())

Today's exercise: Recipe Viewer

Load recipes from a file and view by name or list all.

Steps

  1. 1

    load_recipes()

    Parse blocks separated by blank lines into a dict.

  2. 2

    Menu

    View one recipe or list all names.

Full project source — copy into a folder or use the zip above

starter.py
def load_recipes(path):
    try:
        with open(path, "r") as f:
            blocks = f.read().split("\n\n")
        recipes = {}
        for block in blocks:
            lines = [l.strip() for l in block.split("\n") if l.strip()]
            if len(lines) >= 3:
                name = lines[0]
                ingredients = lines[1].replace("Ingredients:", "").strip()
                instructions = lines[2].replace("Instructions:", "").strip()
                recipes[name] = {"ingredients": ingredients, "instructions": instructions}
        return recipes
    except FileNotFoundError:
        print("Create recipes.txt with name, ingredients, instructions per recipe.")
        return {}

recipes = load_recipes("recipes.txt")
name = input("Recipe name to view: ")
if name in recipes:
    r = recipes[name]
    print(r["ingredients"])
    print(r["instructions"])
else:
    print("Not found. Keys:", list(recipes.keys()))

One rehearsal platform

Certification mocks, daily lessons, project labs, and in-browser drills

Structured for exam day and portfolio proof — timed tests, guided builds, and quick reps on one platform.