← IB Computer Science

B2.5 · Book pp. 378–388

File processing

Your level

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.

Next: files in Python →

B2.5.1 Files in Python

ModeNameWhat happensNote
"r"ReadReads from the start. An error if the file is missingDefault
"w"WriteEmpties the file when opened, or creates itOld content is lost
"a"AppendAdds to the end, or creates the fileOld 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

 

Next: files in Java →

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.

FileRepresents a file: exists(), delete(), getName()
ScannerReads tokens or lines: nextInt(), nextLine(), hasNext()
PrintStreamWrites lines with println()
FileWriterWrites characters. Pass true as the second argument to append
FileReaderReads characters
BufferedReaderReads 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.

Next: topic practice →

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.

 

Next: review →

Quick quiz

1. Why use files?
2. Which mode keeps existing content and adds to it?
3. What does "w" do to an existing file?
4. Reading a file that does not exist…
5. A text file is accessed…
6. f.readline() returns "" when…
7. numbers.txt with no folder is a…

Exam-style questions

These are written for this site in the style of Paper 2. Answer on paper first, then open the mark points.

  1. 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].
  2. 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].
  3. 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].
  4. 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].
  5. 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].