Appendix H — Load and Clean a Wordlist Answers

Completed Check

The loader returns clean labels and ignores input that shouldn’t become a subdomain candidate. Wordlists are just text files, and text files love arriving with blank lines, comments, and trailing newline characters like confetti.

from pathlib import Path

from fixtures.local_targets import course_root


def load_wordlist(path: Path) -> list[str]:
    candidates = []
    with path.open(encoding="utf-8") as file:
        for line in file:
            label = line.strip()
            if not label or label.startswith("#"):
                continue
            candidates.append(label)
    return candidates


labels = load_wordlist(course_root() / "data" / "wordlist.txt")
print(labels[:3])
['www', 'mail', 'ftp']

The normal for loop is intentionally readable here: strip the line, skip blanks and comments, and append only useful labels. A list comprehension can work too, but this shape is kinder when you’re still getting comfortable with file handling.

References: pathlib and Reading and Writing Files.