Rocket's packing list program works perfectly, until he closes IDLE. When he opens it again the next morning, the list is gone, every single item.
"Variables forget everything when the program stops," he sighs. "It is like writing on a steamy mirror."
Raven holds up her notebook, full of pages from months ago. "What do you notice?" she asks. "My notes are still here because I wrote them down somewhere that lasts."
Nova projects a small document icon. "Would you like a hint?" she asks. "Programs can write to files too. A file stays on the computer after the program ends, like a page in your notebook."
Rocket opens the editor to write his very first file.
open("crew.txt", "w") opens a file for writing. The "w" is the mode. If the file does not exist, Python makes it. If it does exist, "w" replaces everything in it.
The with block keeps the file open while its indented lines run, then closes it for you. Inside, f.write(text) writes text into the file.
write does not start a new line by itself. Add \n, the newline character, at the end of each line.
# write_crew.py
with open("crew.txt", "w") as f:
f.write("Rocket\n")
f.write("Raven\n")
f.write("Nova\n")
print("Saved crew.txt") The shell only shows Saved crew.txt. The real result is a new file called crew.txt in the same folder as the program. Inside it are three lines: Rocket, Raven and Nova.
f.write(5) gives a TypeError, because write only accepts strings. Turn numbers into text first, with str(5) or an f-string.
# write_fuel.py
readings = [85, 70, 55]
with open("fuel.txt", "w") as f:
for r in readings:
f.write(f"{r}\n")
print("Wrote", len(readings), "readings") A loop inside the with block can write one line for each item. Here a dictionary of stations becomes a small text report.
# write_report.py
stations = {"Radar": "online", "Fuel": "offline", "Comms": "online"}
with open("report.txt", "w") as f:
f.write("Station report\n")
for name, status in stations.items():
f.write(f"{name}: {status}\n")
print("Report written") Station report Radar: online Fuel: offline Comms: online
| Statement | True or false? |
|---|---|
| f.write(7) works without any change. | ? |
| Mode "w" creates the file if it is missing. | ? |
| The with block closes the file when it ends. | ? |
| print and f.write both send text to the shell. | ? |
Your programs can now leave something behind that lasts. Tomorrow you will read files back in.