Programming foundations

Stage 1 · Lesson 9 of 9

Modules and reading files

Your first language

Programs grow past one file, and real data lives in files. import lets you use : the that ships with Python, such as import random or from pathlib import Path, and your own .py files in the same folder. , if __name__ == "__main__":, runs code only when a file is run directly, not when another file imports it.

That keeps your reusable. For , use with open("data.txt", encoding="utf-8") as f: and loop over f line by line. The with block closes the file for you, even if an error happens halfway.

For each line, strip the newline, split it into fields, convert the types, and be ready for FileNotFoundError. This is exactly what the milestone program needs.

A question to check yourself, an AI practice session and 3 cheat sheet entries come when you add the roadmap to your account. Add it

Resources for this stage

Start with· follow one of these

Practise

  • Small exercises in your language track, with free feedback from a human mentor

Keep handy

  • The official tour: read the matching chapter after the course covers a topic

  • Quick syntax lookups and an online compiler for testing a snippet on a shared computer

Mark this stage as not done?