Why File I/O Matters

Reading and writing files lets programs persist data between runs. In HKDSE ICT, file I/O appears in 70% of papers. Master this topic and you unlock significant marks.

Opening Files

# Basic form
f = open("data.txt", "r")   # read mode
# ... use f ...
f.close()                   # MUST close

# Better form (auto-close)
with open("data.txt", "r") as f:
    # ... use f ...
# automatically closed

Always use with. It closes the file even if errors occur.

File Modes

ModeMeaningBehaviour
"r"ReadDefault. File must exist.
"w"WriteCreates file. Overwrites if exists.
"a"AppendAdds to end. Creates if doesn't exist.
"x"Exclusive createFails if file exists.

Reading Files: 3 Ways

1. Read everything as one string

with open("data.txt") as f:
    content = f.read()
print(content)

2. Read line by line (best for large files)

with open("data.txt") as f:
    for line in f:
        print(line.strip())   # .strip() removes \n

3. Read into a list of lines

with open("data.txt") as f:
    lines = f.readlines()
for line in lines:
    print(line.strip())

Writing Files

# Write a single string
with open("output.txt", "w") as f:
    f.write("Hello, HK!\n")
    f.write("Second line\n")

# Write multiple lines
lines = ["Chan\n", "Lee\n", "Wong\n"]
with open("names.txt", "w") as f:
    f.writelines(lines)

Appending to Files

with open("log.txt", "a") as f:
    f.write("New entry\n")
# Existing content preserved

Real HKDSE Pattern: CSV Processing

# Input file (scores.txt):
# Chan,85
# Lee,72
# Wong,91

students = []

with open("scores.txt") as f:
    for line in f:
        name, score_str = line.strip().split(",")
        students.append((name, int(score_str)))

# Find highest scorer
top = max(students, key=lambda x: x[1])
print(f"Top: {top[0]} with {top[1]}")

# Write sorted list to new file
students.sort(key=lambda x: x[1], reverse=True)
with open("ranked.txt", "w") as f:
    for name, score in students:
        f.write(f"{name}: {score}\n")

Common Mistakes

Reading a File That Might Not Exist

import os

if os.path.exists("data.txt"):
    with open("data.txt") as f:
        content = f.read()
else:
    content = ""   # default

Practise File I/O in PyForm

PyForm supports full file creation, reading, and writing — exactly like HKDSE exam conditions.

Try PyForm →