Reading a file
After this: Open a file, go through its lines, strip the line ends and add the numbers up.
On this page · 6 sections · 3 checks
A file called numbers.txt holds three lines: 3, 5 and 9. Someone wants the total. You could type the three numbers into the Input box from the last lesson, but tomorrow the file has three hundred lines. A program can read the file itself.
A file is lines of text
A text file is text saved under a name. The program sees it as one long string in which every line ends with a line-end character, written \n in code. The file above is the string "3\n5\n9\n". Reading a file means getting that text into the program, and the useful way to get it is one line at a time.
Reading it, step by step
The program below does the job in four steps:
- Start
totalat 0. - Open the file and read all of its lines into a list called
lines: one string per line. In Python, with open("numbers.txt") as f: opens the file under the name f for the indented line below it, and f.readlines() reads the lines. When the indented line has run, the with line closes the file for you.In Java, Files.readAllLines(Path.of("numbers.txt")) opens the file, reads the lines and closes it, all in one line. - Go through the list with a loop. Each
lineis text, so convert it with intInteger.parseInt and add it tototal. - Print
total.
total goes 0, then 3, then 8, then 17, the pattern from Repeating. The only new part is step 2.
The line ends
After readlines, the list is ["3\n", "5\n", "9\n"]: each string still ends with the line-end character, because it was part of the file. strip, from Strings, takes it off, which is why the adding line says int(line.strip()). Print a line without strip and an empty line follows it.readAllLines takes the line ends off for you, so the list is ["3", "5", "9"] and the Java program has no strip. Some files carry spaces at the ends of lines too; trim, from Strings, would take those off.Step through the program. In Python, the trace shows the program going back to the with line once the indented line is done: that is the moment the file is closed. The band words that step as a loop going back; there is no loop, it is the with line finishing.The box lines appears as soon as the reading line has run.
- Run the programRun the program and step through it. Watch the box lines appear with one string per line of the file, then watch total grow as the loop converts and adds each line.
total = 0with open("numbers.txt") as f: lines = f.readlines()for line in lines: total = total + int(line.strip())print(total)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 browser cannot read the files on your computer. The Run block below gives the program a small pretend file called numbers.txt, holding the three lines, and that is the file the program opens.
Add the line print(lines) after the reading line and run it again, to see the list with its line ends.
Where the file is
The program looks for numbers.txt in the folder it is run from, not anywhere on the computer. A file on your desktop is not found when the program runs from another folder. The Run block's pretend folder holds only the files the lesson gives it.
Check yourself
The file numbers.txt holds three lines: 4, 6 and 10. What does this program print?
total = 0with open("numbers.txt") as f: lines = f.readlines()for line in lines: total = total + int(line.strip())print(total)import java.io.IOException;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 { int total = 0; List<String> lines = Files.readAllLines(Path.of("numbers.txt")); for (String line : lines) { total = total + Integer.parseInt(line); } System.out.println(total); }}Complete the missing line so that each line of the file is converted to a number and added to total. With the file from the lesson, the program prints 17.
total = 0with open("numbers.txt") as f: lines = f.readlines()for line in lines: ____________________ # ← add this line's number to totalprint(total)import java.io.IOException;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 { int total = 0; List<String> lines = Files.readAllLines(Path.of("numbers.txt")); for (String line : lines) { ____________________ // ← add this line's number to total } System.out.println(total); }}After the line lines = f.readlines()List<String> lines = Files.readAllLines(Path.of("numbers.txt")); runs on the file from the lesson, what does the box lines hold?
Honesty notes
- Open a file by name and read its lines into a list, one string per line (with open and readlines in Python, Files.readAllLines in Java).
- Say that each line is text and, in Python, still ends with the line-end character, which strip takes off.
- Go through the lines with a loop, convert each one, and add them up.
- Say where the program looks for the file: the folder it is run from.