🎓 A1Learner
🔍
0 of 116 lessons completed

Python Read Files

Reading a file brings the text from disk into a program. A program can read the whole file or walk it line by line.

First, make the poem file

This file is the fixture for this lesson. Create poem.txt first, then read it.

with open("poem.txt", "w") as f:
    f.write("Rain taps on the roof\n")
    f.write("Wind hums through the trees\n")
    f.write("Night brings quiet dreams\n")
print("poem saved")

Read the whole file

read() returns all the text as one string. The end="" stops an extra blank line.

with open("poem.txt", "r") as f:
    text = f.read()
print(text, end="")

Read one line at a time

Each readline() call gives the next line. The newline stays on the line.

with open("poem.txt", "r") as f:
    print(f.readline(), end="")
    print(f.readline(), end="")

Read all lines as a list

readlines() returns a list of lines. strip() cleans one line for printing.

with open("poem.txt", "r") as f:
    lines = f.readlines()
print(len(lines))
print(lines[0].strip())

Loop over the lines

Looping is the usual way to read. strip() removes the trailing newline.

with open("poem.txt", "r") as f:
    for line in f:
        print(line.strip())

Example

with open("poem.txt", "w") as f:
    f.write("Rain taps on the roof\n")
    f.write("Wind hums through the trees\n")
    f.write("Night brings quiet dreams\n")

with open("poem.txt", "r") as f:
    number = 1
    for line in f:
        print(number, line.strip())
        number += 1

Key points

  • Use read() to get the whole file as one string
  • Reading a file loads its text into the program.
  • Use readline() to get one line at a time
  • Use readlines() to get all lines as a list of strings
  • Loop over the file object to walk line by line.
  • This is the usual way.
  • Each line keeps its ending newline.
  • Use strip() to remove it.
  • FileNotFoundError: the error raised when a file name is not found

In this example, the first block creates the poem file. It writes three lines of text. The second block opens the file for reading. The counter number starts at 1. Each loop round prints the number and the clean line. Then the counter grows by one. The output shows all three lines with numbers.

Note

read() loads the whole file into memory at once.

Looping is kinder for big files.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which method reads just one line from a file?