Skip to content
ExamSpine

Lesson 6.7

Open, read, close

Part 6: Errors, testing and filesReading, about 7 min2 exercises in this lesson

Java answers can't run on ExamSpine yet. You can still read Java, trace it, and put an answer's lines in order.

Open, read, close

By the end of this you will be able to open a text file, read what is in it, and close it again, in Python and in Java.

So far every value your programs used was typed in or written in the code. A file lets a program read data that was saved before it ran: a class list, a set of scores, yesterday's results.

How it is asked

Reading and writing files is new in the 2027 course, so no past IB paper has asked about it yet. The syllabus asks you to open a file, read its contents and close it properly. So be ready for two things in Paper 2: writing those lines from memory in your language, and saying what a short program prints for a file you are shown.

Key idea: Open the file, read from it, close it: three steps, every time.

Open, read, close

A school club keeps each member's badge in a file. The file badge.txt holds a name on its first line and a club on its second. Step through the program and watch what each line takes from the file.

Three things happened, in this order:

  • Open: open("badge.txt") in Python, or new FileReader("badge.txt") wrapped in a BufferedReader in Java, finds the file and gets it ready to read. The name is looked up in the working folder: the folder the program is run from, which is not always the folder its code is saved in.
  • Read: each readline() (Java: readLine()) gives back the next line, as text. The file remembers how far you have read.
  • Close: close() tells the system you have finished with the file. A program can only have a limited number of files open at once, so one that keeps opening files and never closes them can run out. When you write to a file, closing it is also what makes sure everything has been saved.

Everything read from a file is text, even a line that holds a number such as 4. To do sums with it you convert it first, which is a later lesson.

The line end

There is one difference between the languages here, and it causes a classic bug. In the file, each line ends with an invisible line end, written \n. Python's readline() keeps it on the end of the text it gives back. Java's readLine() leaves it off.

That is why the Python above calls .strip(): it removes the line end (and any spaces) from both ends of the text.

Let the language close it for you

Forgetting close() is easy, and if a line between open and close raises an exception, the close never runs. Both languages have a way to close the file for you, whatever happens.

with open("badge.txt") as f:
    name = f.readline().strip()
print("Name: " + name)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public static void main(String[] args)
        throws IOException {
    String name;
    try (BufferedReader f = new BufferedReader(
            new FileReader("badge.txt"))) {
        name = f.readLine();
    }
    System.out.println("Name: " + name);
}

In Python this is a with block: the file is open for the indented lines and closed as soon as the block ends, so by the print it is already closed. In Java it is a try-with-resources: the file is made in the brackets after try, and closed at the closing brace. After that brace f no longer exists at all. A variable made inside the braces can only be used there too, so name is made before the try and given its value inside.

Use these from now on. They are shorter, and you cannot forget to close.

Reading the whole file at once

Sometimes you want everything in one go. In Python, f.read() gives back the whole file as one text, line ends and all. In Java, Files.readString(Path.of("badge.txt")) does the same, with import java.nio.file.Files; and import java.nio.file.Path; at the top.

How it is marked

Here is an exam-style question of our own, marked the way IB computer science markschemes mark code: one mark for each point a correct answer must show. Switch to the second script to see where marks are lost.

Now try it yourself on the question below.

Exercise 6.7.16.7.1 · Write itWelcome sign

Write a program that reads a guest's details from the file guest.txt and prints a welcome sign for them.

  1. The first line of guest.txt is the guest's name. The second line is their table number.
  2. Print Welcome, followed by the name and !. Then print Table: followed by the table number.
  3. A name can have spaces inside it, such as Mei Lin, but never at its start or end. A table number is a whole number written with digits.
  4. The file may have more lines after the second one. Ignore them. The last line may or may not end with a line end.

Close the file when you have read it: use with in Python, or try-with-resources in Java. The tests can only check what your program prints, not whether it closed the file, so checking that is up to you.

Your program is run several times, each time in a folder that holds only the files shown for that run.

Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.

Examples

Your program is run 6 times: the 2 examples below, and 4 hidden ones that check the rules above. Only what it prints is checked. Each run starts in an empty folder that holds only the files shown for it.

  • a name, then a table number (rules 1 and 2)

    You type

    Nothing

    It prints

    Welcome, Ana!
    Table: 4

    Files in its folder

    guest.txt
    Ana
    4
  • a name with a space inside it is printed whole (rule 3)

    You type

    Nothing

    It prints

    Welcome, Mei Lin!
    Table: 12

    Files in its folder

    guest.txt
    Mei Lin
    12
solution.pySolution.java

Exercise 6.7.26.7.2 · Answer itScore file two languages

The file scores.txt holds two lines: Kai on the first and 18 on the second, and each line ends with a line end. Two students write the same program, one in Python and one in Java (the Java lines are inside a main that throws IOException, with the imports it needs).

The Python version:

f = open("scores.txt")
player = f.readline()
points = f.readline()
print(player + " scored " + points)

The Java version:

BufferedReader f = new BufferedReader(new FileReader("scores.txt"));
String player = f.readLine();
String points = f.readLine();
System.out.println(player + " scored " + points);

(a) The Python version does not print its message on one line. State the first two lines it prints. [2]

(b) State what the Java version prints. [1]

(c) Both versions leave out one step of using a file. Identify the step, and describe how to change the Python version so that the step happens even if a line raises an exception. [2]

[5]

Report a problem with this page