← IB Computer Science

Files: IB Computer Science practice

Reading and writing text files. 10 questions in the style of the IB Computer Science exam.

Sample questions

Which file mode adds new data to the end of an existing text file without deleting what is already there?

  1. "r"
  2. "w"
  3. "a"
  4. "x"

What does this program print?

with open("scores.csv", "w") as f:
    f.write("Amy,72\nBen,58\nCal,91\n")

best = ""
top = 0
with open("scores.csv") as f:
    for line in f:
        parts = line.strip().split(",")
        if int(parts[1]) > top:
            top = int(parts[1])
            best = parts[0]
print(best, top)

What does this program print?

with open("tasks.txt", "w") as f:
    f.write("wash car\n")
    f.write("buy milk\n")
with open("tasks.txt", "a") as f:
    f.write("call Sam\n")
with open("tasks.txt") as f:
    lines = f.readlines()
print(len(lines))
for i, line in enumerate(lines, start=1):
    print(i, line.strip().title())