Text Files · 2 / 17 Theory

Reading text files

Python offers several ways to read a file. Choose according to what you need to do with the content.

Example file

# notes.txt
first line
second line

third after an empty one

Line by line with for

It is the most usual way and the most efficient: it does not load the whole file into memory.

with open("notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line)

Each line arrives with its final line break (\n), and print adds another: that is why there will be a blank line between each one. To avoid it, remove the break with rstrip:

with open("notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip("\n"))

It is the scheme of Read a text file and More program.

All at once: read()

with open("notes.txt", "r", encoding="utf-8") as f:
    content = f.read()

print(len(content))          # number of characters
print(len(content.split()))  # number of words

read() returns the whole file in a single string. Convenient for small files, as in Count the words in a file. split() without arguments separates by any space or line break.

A list of lines

with open("notes.txt", "r", encoding="utf-8") as f:
    lines = f.read().splitlines()

print(lines)
# ['first line', 'second line', '', 'third after an empty one']

splitlines() already removes the line breaks. It is useful when you are going to query the lines several times, as in Search lines in a text file, where they are read once and then the list is searched as many times as the user asks.

f.readlines() also gives a list, but keeping the \n of each line.

Reading a single line

with open("notes.txt", "r", encoding="utf-8") as f:
    first = f.readline()   # one line; "" when there are no more

Remember: the file is read only once

The file object remembers where it is. If you read everything with read() and read again, you get an empty string:

with open("notes.txt", "r", encoding="utf-8") as f:
    a = f.read()
    b = f.read()
print(len(a) > 0, b == "")   # True True

If you need the content more than once, store it in a variable the first time.