Skip to content
KALANBLON
Show contents

Chapter 3 of 6 · 20 min

Reading and writing text files

By the end of this chapter, you'll be able to

  • Open a file with with open, choosing the right mode
  • Write, append and read text in UTF-8
  • Go through a file line by line
  • Handle a missing file with FileNotFoundError and pathlib

Open, write, close

To work with a file, you open it with open(name, mode, encoding=...). The mode says what you want to do:

  • "r" (the default): read an existing file;
  • "w": write, replacing all the content (the file is created if it doesn't exist);
  • "a": add at the end (append), without erasing what's there.

encoding="utf-8" says how to turn characters into bytes. Always specify it: without it, Python uses the system setting, which varies from one computer to another, and accented letters can become unreadable.

The with statement opens the file and closes it automatically at the end of the block, even if an error occurs. A file that isn't closed properly can lose its last writes.

with open("log.txt", "w", encoding="utf-8") as f:
    f.write("Monday: 3 km\n")
    f.write("Tuesday: 5 km\n")

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("Wednesday: 4 km\n")

with open("log.txt", encoding="utf-8") as f:
    for line in f:
        day, distance = line.strip().split(": ")
        print(day, "→", distance)
Monday → 3 km
Tuesday → 5 km
Wednesday → 4 km
  • f.write(text) writes exactly what you give it: it's up to you to add "\n" to go to the next line.
  • for line in f reads the file one line at a time, which works even for a very big file. Each line ends with "\n": strip() removes it.
  • f.read() reads the whole file at once into a single string.

Closing flushes the buffer to the disk. The data will survive the end of the program.

Step 5 of 5
Text description of the animation
  1. with opens the file for writing. In "w" mode, its old content is erased.
  2. write doesn't necessarily go to the disk straight away: the text waits in a buffer, so that writing happens in big chunks.
  3. The second write joins the first one in the buffer.
  4. End of the with block: the file is closed automatically, even if there was an error.
  5. Closing flushes the buffer to the disk. The data will survive the end of the program.

When the file doesn't exist yet

The very first time the program runs, the save file doesn't exist: opening it for reading raises a FileNotFoundError. That's a normal case, which you handle with try / except.

The pathlib module offers a Path object, handier for working with paths: exists() tests whether the file is there, read_text() and write_text() read or write all the content in one line.

from pathlib import Path

path = Path("scores.txt")
if path.exists():
    path.unlink()

try:
    content = path.read_text(encoding="utf-8")
except FileNotFoundError:
    content = ""
    print("No file yet: starting from scratch")

path.write_text(content + "Awa 12\n", encoding="utf-8")
print(path.read_text(encoding="utf-8").strip())
print(path.exists(), path.suffix)
No file yet: starting from scratch
Awa 12
True .txt

unlink() deletes the file: we use it here so that the example always starts from scratch. suffix gives the file's extension.

Your turn

Worked exercise

Worked exercise: statistics of a text

Write a function statistics(filename) that reads a text file and returns a tuple (number of lines, number of words, most frequent word). Words are counted in lowercase and without attached punctuation (.,!?;:). Test it on a file morning.txt that your program creates itself.

Hint 1
Go through the file with for line in f, and split each line into words with line.lower().split().
Hint 2
word.strip(".,!?;:") removes punctuation at the start and the end. A "word" that becomes empty (like "!") mustn't be counted. For the most frequent one, max(counter, key=counter.get) returns the key with the biggest value.
Show the solution and common mistakes
text = """The sun rises over the river.
The market wakes up, the river shines.
Have a good day!
"""
with open("morning.txt", "w", encoding="utf-8") as f:
    f.write(text)

def statistics(filename):
    lines = 0
    counter = {}
    with open(filename, encoding="utf-8") as f:
        for line in f:
            lines += 1
            for word in line.lower().split():
                word = word.strip(".,!?;:")
                if word:
                    counter[word] = counter.get(word, 0) + 1
    frequent = max(counter, key=counter.get)
    return lines, sum(counter.values()), frequent

print(statistics("morning.txt"))
(3, 17, 'the')

Common mistakes:

  • Forgetting lower(): "The" and "the" would be counted as two different words.
  • Reading with f.read() then counting lines with split("\n"): the last "\n" produces an extra empty line.

Summary

  1. 1with open(name, mode, encoding="utf-8") opens a file and closes it automatically.
  2. 2"r" reads, "w" replaces all the content, "a" adds at the end.
  3. 3for line in f reads a file line by line; strip() removes the line break.
  4. 4A missing file raises FileNotFoundError: the first time a program runs, that's normal.
  5. 5pathlib.Path makes paths simpler: exists(), read_text(), write_text().

Your progress is saved on this device. Create a free account to keep your progress on all your devices.