Step 4 of 6
Save your readings
Right now your data disappears when the program ends. Let’s keep it.
Goal for this lesson: save the readings to a spreadsheet-style file.
CSV: the friendliest file format
A CSV file is plain text with values separated by commas. Spreadsheet programs open it directly, and Python can write it with a built-in tool, so there’s nothing new to install.
Step 1: Add a save function
Add import csv at the top of weather.py, then add save_readings and update the main block. The whole file now looks like this:
import csv
import requests
URL = (
"https://api.open-meteo.com/v1/forecast"
"?latitude=29.42&longitude=-98.49"
"&hourly=temperature_2m&temperature_unit=fahrenheit&forecast_days=2&timezone=auto"
)
def get_forecast():
response = requests.get(URL, timeout=10)
response.raise_for_status()
return response.json()
def hourly_readings(data, count=12):
hourly = data["hourly"]
return list(zip(hourly["time"], hourly["temperature_2m"]))[:count]
def save_readings(readings, path="readings.csv"):
with open(path, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["time", "temperature_f"])
writer.writerows(readings)
if __name__ == "__main__":
readings = hourly_readings(get_forecast())
save_readings(readings)
print(f"Saved {len(readings)} readings to readings.csv")
Step 2: Run it and look
python3 weather.py
You should see Saved 12 readings to readings.csv. Open readings.csv in any spreadsheet program or text editor. Your forecast is now a file you own.
Check yourself
The first row of the file should say time,temperature_f, followed by 12 rows of data. If the file is empty, make sure you saved weather.py before running it.