Writing a file
After this: Save a list to a file, read it back, and say what happens to the old contents.
On this page · 5 sections · 3 checks
The program from the last lesson worked out a total, printed it, and ended. The moment a program ends, its boxes are gone. To keep a result, a list the person typed in, or a score, the program has to put it somewhere that lasts: a file.
Writing, step by step
Writing is the mirror of reading. Open the file for writing, put text into it, close it. The program below saves three names, one per line, and then reads the file back to show what landed in it.
- Open
names.txtfor writing. In Python that is open("names.txt", "w"): the "w" says writing.In Java that is new PrintWriter("names.txt"), a tool for writing text. At this moment the file exists and is empty. - For each name in the list, write the name and end the line. write puts in exactly the text you give it and nothing more, so the "\n" is needed. Without it the three names land on one line: AnaBenCy.println writes the text and ends the line, as it does on the screen.
- When the indented lines are done, the file is closed. The trace shows the program going back to the with line: that is the close. The band words it as a loop going back; there is no loop, it is the with line finishing.The trace shows the program going back to the try line: that is the close. The band words it as a loop going back; there is no loop, it is the try line finishing.
- Open the file again, for reading this time, and print its lines. Three names come back.
names = ["Ana", "Ben", "Cy"]with open("names.txt", "w") as f: for name in names: f.write(name + "\n")with open("names.txt") as f: lines = f.readlines()for line in lines: print(line.strip())run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The Run block works in a pretend folder that starts empty. The program creates names.txt there, and the file is gone when you leave the page.
Add a fourth name to the list and run it again.
What happens to the old contents
Opening a file for writing replaces everything. If names.txt already held a hundred names, then after open("names.txt", "w")new PrintWriter("names.txt") it holds nothing, before a single write has happened. There is no message and no undo. Check the name of the file before you open it for writing.
To keep the old lines and add new ones at the end, open the file a different way; the honesty note at the end shows it.
Why closing matters
What you write does not always reach the disk at once. The program gathers text and hands it over in batches, and the last batch goes when the file is closed. A file that is never closed can be missing its last lines. The with line closes the file for you when its indented lines finish, even when an error happens inside them.The try line with brackets closes the file for you when its block finishes, even when an error happens inside it. Use that form, and you never forget.
Check yourself
report.txt holds yesterday's report, fifty lines. A program opens it for writing with open("report.txt", "w")new PrintWriter("report.txt") and writes one line. What does the file hold afterwards?
Complete the missing line so that names.txt is opened for writing, as the box fout, and the three names are written into it. The program then reads the file back and prints 3.
names = ["Ana", "Ben", "Cy"]____________________ # ← open names.txt for writing, as the box f for name in names: f.write(name + "\n")with open("names.txt") as f: lines = f.readlines()print(len(lines))import java.io.IOException;import java.io.PrintWriter;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class Main { public static void main(String[] args) throws IOException { List<String> names = List.of("Ana", "Ben", "Cy"); ____________________ // ← open names.txt for writing, as the box out for (String name : names) { out.println(name); } } List<String> lines = Files.readAllLines(Path.of("names.txt")); System.out.println(lines.size()); }}The file log.txt does not exist before the program runs. What does the program print?
with open("log.txt", "w") as f: f.write("one\n") f.write("two\n")with open("log.txt", "w") as f: f.write("three\n")with open("log.txt") as f: lines = f.readlines()print(len(lines))print(lines[0].strip())import java.io.IOException;import java.io.PrintWriter;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class Main { public static void main(String[] args) throws IOException { try (PrintWriter out = new PrintWriter("log.txt")) { out.println("one"); out.println("two"); } try (PrintWriter out = new PrintWriter("log.txt")) { out.println("three"); } List<String> lines = Files.readAllLines(Path.of("log.txt")); System.out.println(lines.size()); System.out.println(lines.get(0)); }}Honesty notes
- Open a file for writing and write lines into it (open with "w" and write in Python, a PrintWriter inside try with brackets in Java).
- Say plainly that opening a file for writing replaces its old contents, before anything is written.
- Let the with line (the try line in Java) close the file when its lines are done, and say why closing matters.
- Read the file back in the same program to check what landed in it.