← All lessons

Reading line by line

Sign in · Sign up

Lesson 9.4

A file can be read one line at a time:

with open("notes.txt", encoding="utf-8") as f:
    for i, line in enumerate(f, start=1):
        print(i, line.strip())
  • for line in f: gives the lines one after another;
  • enumerate(f, start=1) numbers them from one;
  • line.strip() removes the \n at the end — otherwise blank lines appear between the lines.

readline() reads one line, readlines() reads them all at once as a list. Looping over the file is the simplest of all.

The check sets the file name filename and its contents content. Print each line as <number> <text>, numbered from 1.

Hint

enumerate(f, start=1) gives the number and the line at once.

The line contains a \n at the end, so .strip() is needed. A print with two arguments puts a space between them.