← Back to course
Code Crew G6+ / Week 08 / Crew Quest
6/6
Week 08 Β· Files

Crew Quest

Crew Quest: Weather log
// Saving work that lasts
⏱ about 30 min

Saturday: Crew Quest: Weather log

Raven has kept a weather notebook for years: one line a day, with the sky and the temperature. Rocket thinks the notebook should have a program to go with it.

"Every morning, type the weather once," he says. "The program adds it to a file and tells you the warmest day so far."

Raven nods slowly. "What do you notice about my notebook?" she asks. "Every line has the same shape. That is what makes it easy for a program to read."

Nova draws one line split into labeled parts. "Interesting," she says. "Decide the shape of a line before you write the first one. Then every line agrees."

Rocket and Raven agree on a shape: sky, a comma, then the temperature.

  1. with open(name, mode) as f: opens a file and closes it at the end of the block.
  2. "w" writes fresh, "a" adds to the end, and "r" (the default) reads.
  3. write needs a string, and \n ends each line.
  4. Use .strip() on lines you read to remove the newline.
  5. Files appear in the same folder as the program when you run it from IDLE.
# weather.py
sky = input("Sky today: ").strip()
temp = int(input("Temperature: "))
with open("weather.txt", "a") as f:
    f.write(f"{sky},{temp}\n")

warmest = None
with open("weather.txt") as f:
    for line in f:
        parts = line.strip().split(",")
        t = int(parts[1])
        if warmest is None or t > warmest:
            warmest = t
print("Warmest so far:", warmest)

The split(",") method cuts a string at every comma and gives a list of the pieces. So "sunny,24".split(",") gives ["sunny", "24"].

warmest starts as None, which means no value yet. The test warmest is None is True only until the first temperature is stored.

With two earlier days already in the file, a run looks like this:

Sky today: rainy
Temperature: 17
Warmest so far: 24
What does "cloudy,19".split(",")[1] give?
WHY THIS EXERCISEsplit cuts at the comma, and index 1 picks the second piece, the string 19.
β—‡ START A REAL WEATHER LOG
With a grown-up, run weather.py once a day for a week, using your local weather.
Each day, predict the warmest so far before you press Enter on the temperature.
At the end of the week, open weather.txt together and read every line.
MORE REVIEW: WEEK 8
  • Read the question.
  • Tap your answer.
Which mode adds to a file without erasing it?
What does "sunny,24".split(",") give?
Why use .strip() on each line read from a file?

Excellent work. Next week you will save whole lists and dictionaries in one go with JSON.

← Friday