
Code
Line by Line
A file object is iterable: a for loop hands you one line at a
time. This works even for files far too big to fit in memory.
with open("beacons.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
line = line.strip() # remove "\n" and spaces
if not line or line.startswith("#"):
continue # skip blanks & comments
print(number, line)
Each line still ends with "\n", so .strip() it first.
To split "Gull Rock: dark: needs oil" into a name and a status,
use line.split(":", 1). The 1 means "split at the first
colon only", giving ["Gull Rock", " dark: needs oil"].
If the file isn't there, open() raises FileNotFoundError, and
you already know how to catch that!
Assignment
Complete read_beacons(path). Each line of the file looks like
island: status.
- Skip blank lines and lines starting with
#. - Return a dict mapping each island to its status, both with spaces stripped. Split only at the first colon.
- If the file doesn't exist, return an empty dict
{}.
Complete read_beacons(path). Each line of the file looks like
island: status.
- Skip blank lines and lines starting with
#. - Return a dict mapping each island to its status, both with spaces stripped. Split only at the first colon.
- If the file doesn't exist, return an empty dict
{}.
main.py Python sleeping
Press Run to try your code, then Check to test it.