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

Monday

Writing a file
// Saving work that lasts
⏱ about 30 min

Monday: Writing a file

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, write and with

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.

WHERE DID IT GO?
  • Read the question.
  • Tap your answer.
When you run write_crew.py from IDLE, where does crew.txt appear?
You run write_crew.py twice. How many lines does crew.txt have?

Write needs a string

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")
How many lines does fuel.txt have after write_fuel.py runs?
What is the first line of fuel.txt?
For a grown-up
This week the programs create small text files in the mission folder. They only touch files in that folder, by name.
If your learner cannot find a file, open the mission folder in the computer's file browser together. Text files open in any plain text editor.
At your computer
1. Type write_crew.py, save it in your mission folder and run it.
2. Open your mission folder in the computer's file browser. Find crew.txt.
3. In IDLE, choose File, then Open, and open crew.txt to see the three lines. You may need to show all files in the Open box.
4. Type write_fuel.py, save it and run it. Then open fuel.txt.
5. Change one name in write_crew.py, run it, and open crew.txt again.

Practice: write a report from a dictionary

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
READ WRITE_REPORT.PY
  • Read the question.
  • Tap your answer.
How many lines does report.txt have?
What does the shell show when it runs?
What happens if you forget the \n in the loop?
What is the third line of report.txt?
You add "Medical": "online" to the dictionary. How many lines now?
What does f.write(str(42) + "\n") write on the line?
StatementTrue 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.?
WHY THIS EXERCISEwrite only takes strings and writes to the file, while print shows text in the shell.

Your programs can now leave something behind that lasts. Tomorrow you will read files back in.