This content can't be printed from the browser. Use Export PDF with Pro for an offline copy.
IB Syllabus Requirements for File processing
B2.5.1
Constructing file-processing code
B2.5.1
CONSTRUCTING FILE-PROCESSING CODE
Construct file-processing code by choosing an opening mode, performing the required reads or writes, and closing the file when finished. Your program must distinguish between replacing existing contents and adding to them.
A text file stores characters, including line breaks, that a program can read and write. Unlike values held only in program variables, saved file contents remain available after the program finishes.
With sequential access, a program reads the file in order from its current position. Reading advances that position; reading a line does not remove it from the file. To reach a later line, the program reads through the preceding lines.
Choose the mode before opening the file. In particular, write mode and append mode have different effects on an existing file.
| Mode | Purpose | If the file exists | If the file does not exist |
|---|---|---|---|
| Read | Retrieve existing text | Contents remain unchanged; reading starts at the beginning | Opening fails |
| Write | Save replacement text | Existing contents are discarded when the file is opened | A new file is created |
| Append | Add text at the end | Existing contents are preserved | A new file is created |
Writing text does not automatically insert a line break. Include a newline character when each item should occupy its own line.
Java can use Scanner to read text and FileWriter to write or append text. BufferedReader is another available class for reading text; other suitable classes also exist.
Python uses open() to obtain a file object. Its mode is specified by a string: "r" for read, "w" for write, or "a" for append.
| Operation | Java approach | Python approach |
|---|---|---|
| Open for reading | Construct a Scanner using a File | Call open() with read mode |
| Read sequentially | Check hasNextLine(), then call nextLine() | Call readline() repeatedly, or iterate over the file |
| Read all remaining text | Read repeatedly and collect the text | Call read() |
| Open for writing | Construct a FileWriter; write mode is the default | Call open() with write mode |
| Open for appending | Construct a FileWriter with its append argument set to true | Call open() with append mode |
| Write text | Call write() on the writer | Call write() on the file object |
| Close | Call close() on the reader or writer | Call close() on the file object |
Python's readline() returns one line, including its ending newline if present. At the end of the file it returns an empty string. A blank line returns a newline character, not an empty string, so it must not be mistaken for the end of the file.
Java's nextLine() returns the line without its ending newline. Check hasNextLine() before reading so that the program does not try to read beyond the available lines.
A school equipment store saves item names in a file named equipment.txt. These equivalent programs first replace its contents with Rope and Lamp, close it, append Tent, close it again, then read and display every item. They create their own starting data, so no prepared input file is needed.
Java
1 import java.io.File;
2 import java.io.FileWriter;
3 import java.io.IOException;
4 import java.util.Scanner;
5 public class EquipmentFile {
6 public static void main(String[] args) throws IOException {
7 FileWriter writer = new FileWriter("equipment.txt");
8 writer.write("Rope
");
9 writer.write("Lamp
");
10 writer.close();
11 FileWriter appender = new FileWriter("equipment.txt", true);
12 appender.write("Tent
");
13 appender.close();
14 Scanner reader = new Scanner(new File("equipment.txt"));
15 while (reader.hasNextLine()) {
16 String line = reader.nextLine();
17 System.out.println(line);
18 }
19 reader.close();
20 }
21 }
Python
1 writer = open("equipment.txt", "w")
2 writer.write("Rope
")
3 writer.write("Lamp
")
4 writer.close()
5 appender = open("equipment.txt", "a")
6 appender.write("Tent
")
7 appender.close()
8 reader = open("equipment.txt", "r")
9 line = reader.readline()
10 while line != "":
11 print(line, end="")
12 line = reader.readline()
13 reader.close()
Java line 7 opens in write mode; line 11 enables append mode using true. The declaration involving IOException allows file-operation errors to be reported by this short example.
Python lines 1, 5 and 8 select write, append and read modes respectively. Line 11 avoids adding another newline because the line read from the file already includes one.
In the table, represents a newline character, and a dash means that no value or output applies at that stage. The output column records only the new output produced at that step.
| Step | File contents | Java variable line | Python variable line | New output |
|---|---|---|---|---|
| Open in write mode | Empty | — | — | — |
| Write first item | `Rope | |||
| ` | — | — | — | |
| Write second item and close | `Rope\nLamp | |||
| ` | — | — | — | |
| Append third item and close | `Rope\nLamp\nTent | |||
| ` | — | — | — | |
| Read and display first line | Unchanged | "Rope" | `"Rope | |
| "` | Rope | |||
| Read and display second line | Unchanged | "Lamp" | `"Lamp | |
| "` | Lamp | |||
| Read and display third line | Unchanged | "Tent" | `"Tent | |
| "` | Tent | |||
| Detect end of file | Unchanged | "Tent"; hasNextLine() is false | "" | — |
Both programs display Rope, Lamp and Tent on separate lines. Neither reading nor closing the reader changes the saved text.
Close a writer before opening a reader for the same file so that pending output is available for reading. Close the reader after its loop has finished.
Opening in write mode inside a repeated operation can accidentally erase earlier output. To add several records, either keep one writer open while writing them all or use append mode when reopening the file.
Terms to use: text files, sequential file, read, write, append, close.