Problem 1 โ Count Lines
with open("notes.txt") as f:
print(sum(1 for _ in f))
Problem 2 โ Read Into List
with open("scores.txt") as f:
scores = [int(line) for line in f]
Problem 3 โ Append a Log Entry
from datetime import datetime
with open("log.txt", "a") as f:
f.write(f"{datetime.now()}: started\n")
Problem 4 โ Word Frequency
from collections import Counter
with open("article.txt") as f:
words = f.read().lower().split()
print(Counter(words).most_common(5))
Problem 5 โ Filter and Rewrite
with open("in.txt") as f, open("out.txt", "w") as g:
for line in f:
if not line.strip().startswith("#"):
g.write(line)
Problem 6 โ CSV Totals
import csv
with open("sales.csv") as f:
reader = csv.DictReader(f)
total = sum(float(row["amount"]) for row in reader)
print(f"Total: ${total:.2f}")
๐ก Always use the
with block. It guarantees the file is closed even if an exception is raised.Practise this on PyForm โ free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm โ