Reading files line by line

18-minute lesson · module-files-02

You are previewing this course as a guest

Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.

Sign in

Reading files line by line

18-minute lesson · module-files-02

  • Read an entire file with `.read()` and a list of lines with `.readlines()`.
  • Iterate a file object directly to process one line at a time.
  • Strip the trailing newline from each line with `.strip()`.
  • Convert text lines into numbers and aggregate them.

Source attribution

Status: adapted

How to Think Like a Computer Scientist: Interactive Edition source · Files / Reading a File / Iterating over lines / Alternative File Reading Methods

Adaptation notes. Reading rewritten in our voice. The scores-file example is ours. The coding exercise takes a path argument and the test creates the input file in /tmp first, so it runs identically in Pyodide and a local subprocess.

License notes. Original chapter is GNU FDL 1.3 (Brad Miller, David Ranum, and the upstream Elkner/Downey/Meyers text). No verbatim text reproduced.