Clastify logo
Subjects
Features
Review
HOT
Tutoring

B2.5: File processing

Master IB Computer Science B2.5: File processing with notes created by examiners and strictly aligned with the syllabus.

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.

Text files and sequential access

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.

The figure shows the processing sequence: open, read or write, then close. Opening makes the file available in the selected mode; closing releases the file resource and ensures any buffered output is passed on for saving.

Choosing an opening mode

Choose the mode before opening the file. In particular, write mode and append mode have different effects on an existing file.

ModePurposeIf the file existsIf the file does not exist
ReadRetrieve existing textContents remain unchanged; reading starts at the beginningOpening fails
WriteSave replacement textExisting contents are discarded when the file is openedA new file is created
AppendAdd text at the endExisting contents are preservedA 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.

File operations in Java and Python

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.

OperationJava approachPython approach
Open for readingConstruct a Scanner using a FileCall open() with read mode
Read sequentiallyCheck hasNextLine(), then call nextLine()Call readline() repeatedly, or iterate over the file
Read all remaining textRead repeatedly and collect the textCall read()
Open for writingConstruct a FileWriter; write mode is the defaultCall open() with write mode
Open for appendingConstruct a FileWriter with its append argument set to trueCall open() with append mode
Write textCall write() on the writerCall write() on the file object
CloseCall close() on the reader or writerCall 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.

Worked example: write, append, then read

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.

Trace of the worked example

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.

StepFile contentsJava variable linePython variable lineNew output
Open in write modeEmpty———
Write first item`Rope
`———
Write second item and close`Rope\nLamp
`———
Append third item and close`Rope\nLamp\nTent
`———
Read and display first lineUnchanged"Rope"`"Rope
"`Rope
Read and display second lineUnchanged"Lamp"`"Lamp
"`Lamp
Read and display third lineUnchanged"Tent"`"Tent
"`Tent
Detect end of fileUnchanged"Tent"; hasNextLine() is false""—

Both programs display Rope, Lamp and Tent on separate lines. Neither reading nor closing the reader changes the saved text.

Closing and preserving the intended contents

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.

Were those notes helpful?

B2.4 Programming algorithms