File handling — Practice worksheet
Tip: Press S to toggle all answers
Exercise 1 — Count words
Write a function count_words(path) that returns the number of words in a UTF-8 text file.
Answer (click to open)
def count_words(path):
with open(path, 'r', encoding='utf-8') as f:
text = f.read()
return len(text.split())
Exercise 2 — Replace text safely
Create replace_in_file(path, old, new) that replaces all occurrences of old with new safely (write to a temp file then replace).
Answer (click to open)
from pathlib import Path
import tempfile
import shutil
def replace_in_file(path, old, new):
path = Path(path)
with tempfile.NamedTemporaryFile('w', delete=False, encoding='utf-8') as tmp:
with path.open('r', encoding='utf-8') as r:
for line in r:
tmp.write(line.replace(old, new))
shutil.move(tmp.name, str(path))
Exercise 3 — Merge files
Implement merge_files(outpath, *paths) concatenating multiple files to outpath.
Answer (click to open)
from pathlib import Path
def merge_files(outpath, *paths):
out = Path(outpath)
with out.open('w', encoding='utf-8') as w:
for p in paths:
with open(p, 'r', encoding='utf-8') as fh:
for line in fh:
w.write(line)
Exercise 4 — File existence & safe delete
Write a function safe_remove(path) that deletes path only if it's inside a permitted directory (avoid deleting arbitrary paths).
Answer (click to open)
from pathlib import Path
ALLOWED_DIR = Path('data').resolve()
def safe_remove(path):
p = Path(path).resolve()
if ALLOWED_DIR in p.parents or p == ALLOWED_DIR:
if p.exists():
p.unlink()
return True
return False
Exercise 5 — Read large file lazily
Show how to process a large file line-by-line without loading it all to memory (e.g. count lines that contain the word "error").
Answer (click to open)
def count_error_lines(path):
count = 0
with open(path, 'r', encoding='utf-8') as f:
for line in f:
if 'error' in line.lower():
count += 1
return count