Question bank › IB Computer Science › B2 Programming

File processing

Answer on paper first, then reveal the mark scheme one mark at a time.

1Hard6 marks

A text file scores.txt stores one integer test score on each line, for example:

60
75
90

Write a Python function average_score(filename) that:

  • returns the mean of all the scores in the file;
  • returns 0 if the file contains no scores;
  • returns None if the file does not exist.

[6]

2Core5 marks

A program opens a text file using Python's open() function.

(a) For each of the modes "r", "w" and "a", state what happens when the program opens a file that already exists and contains data. [3]

(b) State what happens when a file that does not exist is opened in "r" mode. [1]

(c) Outline one reason why a program should close a file once it has finished with it. [1]

3Core4 marks

The text file planets.txt contains four lines. Every line, including the last, ends with a newline character.

Mercury
Venus
Earth
Mars

The following Python code is run.

f = open("planets.txt", "r")
a = f.readline()
b = f.readline().strip()
rest = f.read()
f.close()
print(len(a), b)
print(rest.count("\n"))

(a) State the exact output of the program. [3]

(b) Distinguish between the methods readline() and read(). [1]

Stuck on File processing?

Get it sorted in a free 30-minute session

We work through your weakest questions on this topic on Zoom. I reply the same day.

4Standard5 marks

A teacher wants to save a class register to a text file, one name per line. She writes this Python code.

names = ["Ava", "Ben", "Cal"]
for n in names:
    f = open("register.txt", "w")
    f.write(n + "\n")
    f.close()

(a) State the contents of register.txt after the code has run. [1]

(b) Explain why the file does not contain the whole register. [2]

(c) Construct a corrected version of the code so that all three names are saved, the file is opened only once and any previous contents of the file are replaced. [2]

5Standard5 marks

The following Java code writes the square numbers 1, 4, 9 and 16 to a text file.

FileWriter fw = new FileWriter("squares.txt");
for (int i = 1; i <= 4; i++) {
    fw.write(String.valueOf(i * i));
}
fw.close();

(a) State the exact contents of squares.txt after the code has run. [1]

(b) Construct the change needed to line 3 so that each number is stored on its own line. [1]

(c) A student deletes the statement fw.close();. Explain the effect this could have on squares.txt. [2]

(d) State how line 1 should be changed so that running the program again adds to the end of the file instead of replacing it. [1]

6Standard5 marks

A shop stores its stock in the text file stock.txt. Each line holds an item name and the quantity in stock, separated by a comma.

pens,40
rulers,0
glue,12
erasers,0

The following Java code processes the file.

BufferedReader br = new BufferedReader(new FileReader("stock.txt"));
String line = br.readLine();
int out = 0;
while (line != null) {
    String[] parts = line.split(",");
    int qty = Integer.parseInt(parts[1]);
    if (qty == 0) {
        System.out.println(parts[0]);
        out++;
    }
    line = br.readLine();
}
br.close();
System.out.println(out + " out of stock");

(a) State the output of the code. [2]

(b) State the value returned by br.readLine() when the end of the file has been reached. [1]

(c) Explain what would happen if the statement line = br.readLine(); inside the loop were deleted. [2]

7Hard6 marks

A weather station records one temperature reading per line in the text file readings.txt, for example:

18.5
21.0
23.4
19.9
25.1

Construct a Python function copy_warm(threshold) that:

  • reads every reading from readings.txt;
  • writes each reading that is greater than or equal to threshold to a new file warm.txt, one reading per line, replacing any previous contents of warm.txt;
  • closes both files and returns the number of readings written.

For the example file, copy_warm(21.0) should return 3. You may assume the file exists and every line holds a valid number. [6]

8Hard5 marks

A program keeps a log in the text file log.txt. Before the program runs, the file contains one line, boot, followed by a newline. The program defines and uses this procedure.

def log(msg, mode):
    f = open("log.txt", mode)
    f.write(msg + "\n")
    f.close()

log("start", "a")
log("load", "a")
log("reset", "w")
log("run", "a")

f = open("log.txt", "r")
lines = f.readlines()
f.close()
print(len(lines))
print(lines[-1].strip())

(a) Deduce the contents of log.txt immediately before the call log("reset", "w"). [1]

(b) Deduce the contents of log.txt at the end of the program. [2]

(c) State the output of the program. [2]

9Stretch7 marks

A school library exports its overdue loans to the text file loans.txt. The first line is a header; each following line holds a student ID, a book title and the number of days overdue, separated by commas.

studentID,title,daysOverdue
S104,Dune,3
S221,Emma,0
S104,Ulysses,40
S318,Kim,12

The fine for a loan is 0.20 per day overdue, up to a maximum of 5.00 per loan. The file fines.txt already holds fines from earlier weeks, which must be kept.

Construct code in Python or Java that:

  • ignores the header line;
  • for every loan with at least one day overdue, adds a line studentID,fine to the end of fines.txt, with the fine to 2 decimal places (for example S104,0.60);
  • outputs the total of the new fines once all loans have been processed;
  • closes both files.

You may assume loans.txt exists and is correctly formatted. [7]

10Stretch6 marks

The text file notes.txt contains the four lines below; the second line is blank. Every line ends with a newline character.

alpha

beta
gamma

The following Python code is run.

f = open("notes.txt", "r")
count = 0
line = f.readline()
while line != "":
    count = count + 1
    line = f.readline()
f.close()
print(count)

(a) State the output. [1]

(b) Explain why the loop does not stop when it reaches the blank line. [2]

(c) A student changes the loop condition to while line.strip() != "":. State the new output. [1]

(d) Construct a change to the original code so that it counts only the lines that are not blank, while still reading the whole file. [2]

Stuck on this topic?

Book a free 30-minute session on WhatsApp and we'll find exactly which step is costing you the marks. Or build a timed paper on it.

Free 30-minute session