04 / FILES AND FORMATS · LESSON 13

Read and write text files

Transform a supplied file and save a repeatable text report.

14 min · learn at your pace

Work in the virtual filesystem

The lab starts in /home/user. A relative path such as assets/hosts.txt is resolved from that working directory. pathlib.Path provides readable operations for building paths, making directories, and reading or writing files.

Use Path("output").mkdir(parents=True, exist_ok=True) before writing into a new directory. write_text() replaces a file’s content. Appending is useful for a log, but a report should usually replace its previous version so repeated runs do not duplicate records.

Make text boundaries explicit

Specify encoding="utf-8" for portable text, particularly when names include accents. splitlines() handles line endings without leaving newline characters on each value. Strip surrounding whitespace, then decide what to do with blank lines or duplicates.

These files exist inside the browser runtime, not on your laptop. Completed snapshots save with the lesson draft in first-party browser storage. Check replaces the workspace with the original fixtures. Keep source data unchanged: write the cleaned result to a separate output path so you can trace a report back to its input.

Try an example.py
from pathlib import Path
output = Path("output")
output.mkdir(exist_ok=True)
(output / "hello.txt").write_text("Hello, files!\n", encoding="utf-8")
print((output / "hello.txt").read_text(encoding="utf-8"))
YOUR TURN

Put it into practice.

Read assets/hosts.txt as UTF-8. Strip each line, lowercase nonempty names, remove duplicates, and sort ascending. Write output/hosts.txt with one name per line and a final newline (or an empty file when there are no names). Leave the source unchanged.

See an explained solution
One way to solve it.py
from pathlib import Path
source = Path("assets/hosts.txt")
names = sorted({line.strip().lower() for line in source.read_text(encoding="utf-8").splitlines() if line.strip()})
Path("output").mkdir(parents=True, exist_ok=True)
Path("output/hosts.txt").write_text("".join(name + "\n" for name in names), encoding="utf-8")

The set removes duplicates after normalisation. The output directory can already exist, and write_text replaces the report, so repeated runs are predictable.