B2.5 · Book pp. 378–388
File processing
Variables vanish when a program ends. Files let your data survive, which your internal assessment will probably need.
What you need to know
- B2.5.1 Construct code to perform file-processing operations.
The steps are always the same: open, read or write, close.
An absolute path gives the full location from the root folder. A relative path starts from the current folder, so numbers.txt needs the file to be there.
B2.5.1 Files in Python
| Mode | Name | What happens | Note |
|---|---|---|---|
"r" | Read | Reads from the start. An error if the file is missing | Default |
"w" | Write | Empties the file when opened, or creates it | Old content is lost |
"a" | Append | Adds to the end, or creates the file | Old content is kept |
f.read() | The whole file as one string |
f.readline() | One line, or "" at the end of the file |
for line in f: | Each line in turn |
f.write(text) | Writes text, without adding a new line |
f.close() | Finishes and saves the data |
These programs use a private, temporary disk inside your browser. Nothing is saved to your computer.
✏️ Book corrections
- It says each new text in write mode overwrites what is there. Opening with "w" empties the file once. Further writes then add after each other, as the first program shows.
- It says its loop reads until a line is blank. readline() returns "" only at the end of the file. A blank line in the middle is "\n", so reading continues.
- Its examples never close the file after reading. Use
with, or call close() yourself.
Handling problems
✍️ Try it: a run counter
B2.5.1 Files in Java
You only need this if your school examines Java. Import java.io.* and java.util.*, and wrap file code in try/catch.
| File | Represents a file: exists(), delete(), getName() |
| Scanner | Reads tokens or lines: nextInt(), nextLine(), hasNext() |
| PrintStream | Writes lines with println() |
| FileWriter | Writes characters. Pass true as the second argument to append |
| FileReader | Reads characters |
| BufferedReader | Reads efficiently with readLine(), which gives null at the end |
✏️ Book correction
The book says nextLine() splits input into tokens. It is next(), nextInt() and nextDouble() that read tokens, while nextLine() reads the whole line.
Practice across B2
Trace it
Trace this for "car,boat,ball", with columns value, pos, letter and output, then run it.
Answer
It splits a string at commas, and prints each item on its own line. "a,,b" prints a blank line, and "a, b" keeps a leading space.
Round-robin tournament
This combines 2D arrays, parallel arrays, sorting and files, much like a long Paper 2 question.
Quick quiz
Exam-style questions
These are written for this site in the style of Paper 2. Answer on paper first, then open the mark points.
-
A file marks.txt holds one integer per line. Construct code that outputs the average. [4]
Mark points
- Open the file for reading [1].
- Loop over lines, adding int(line) to a total and counting [1].
- Close the file [1].
- Output total ÷ count [1].
-
Parallel lists NAMES and SALES are held in memory. Construct code to save them to one file, as name,sale lines. [4]
Mark points
- Open the file in write mode [1].
- Loop over the indexes [1].
- Write name, a comma, the sale as a string and "\n" [1].
- Close the file [1].
-
Outline why exception handling should be used with files. [3]
Mark points
- The file may be missing, or locked [1].
- This would otherwise stop the program [1].
- try/except lets it report the problem and carry on [1].
-
Distinguish between write mode and append mode. [2]
Mark points
- Write mode replaces the file’s content [1].
- Append mode adds to the end, keeping the content [1].
-
A 2D list SCORES gives the points of row player against column player. Construct code that prints the winner of every pair. [6]
Mark points
- Two nested loops over players [1].
- Start the inner loop after the outer index, so each pair appears once [1].
- Read SCORES[i][j] and SCORES[j][i] [1].
- Compare them [1].
- Output the winner’s name from NAMES [1].
- Output a tie message when equal [1].