Space Python Loading Python…

Log to a file

Write the codeEasy 2 stages

The mission log has lived in a Python list, which disappears the moment the program ends. Tomorrow's shift wants to read what happened today, and the flight director wants a file she can send to the agency.

Write the log to mission.log, read it back to make sure it is all there, then keep adding to it.

Write each entry to mission.log, one per line, with with open("mission.log", "w", encoding="utf-8") as log_file:. Then open the file again, read it line by line and print each line without its line break:

[T+00:10:00] INFO  Orbit insertion complete
[T+00:12:05] WARN  Battery 3 temperature high
[T+00:14:47] ERROR Fuel valve 2 not responding

The hidden tests also open mission.log and check what is in it.

The log, read from the file
The file itself

Finish stage 1 to unlock this stage.

Opening with "w" again would wipe the log. Write append_entry(entry), which opens the file with "a" and adds one line at the end. Add the new entry with it, then read the file back, print it, and count its lines:

[T+00:10:00] INFO  Orbit insertion complete
[T+00:12:05] WARN  Battery 3 temperature high
[T+00:14:47] ERROR Fuel valve 2 not responding
[T+00:15:42] WARN  Star tracker lost lock
Entries in mission.log: 4

log_file.readlines() gives a list of the lines, so len() counts them.

Four entries
append_entry() keeps the rest
You're not logged in, so your progress is kept in this browser only. Log in to save it, and to use hints and solutions.

Hints

Import System Modules

import-system-modules.py
# A module is a toolbox someone else already built and tested for you

# Plain import brings in the whole module
import sys
import platform
import math

# from ... import brings in just one tool
from math import sqrt

# as gives a module a shorter nickname
import random as rng

# With a plain import: module name, a dot, then the tool
print("Python version:", platform.python_version())
print("Running on:", platform.system())
print("Python lives at:", sys.executable)

# math carries constants you would not want to type from memory
radius_km = 6371
print("Earth circumference:", round(2 * math.pi * radius_km), "km")

# sqrt arrived on its own, so it needs no dot in front
print("Square root of 9:", sqrt(9))

# rng is simply a nickname for random
print("Random sol of the Martian year:", rng.randint(1, 687))
Open the full example
script.py
PythonLn 1, Col 1Spaces: 4
Loading the Python environment…

Separate arguments with commas. They're passed on every Run as sys.argv[1:].