Skip to content
Theory · Modules, files and generators · lesson 4 of 12

Files and with

Variables are like chalk notes on a board. While the program runs, you can read and erase them. When the program ends, the board is wiped clean, and on the next run it is empty.

For data to survive until the next run, it is written to a file. A file is a notebook in a desk drawer: you open it, write, close it and put it back, and the notes stay. The built-in function open opens the notebook.

Course exercises run in the browser, which cannot see your files. So run these examples on your computer, in a separate folder:

Python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("milk\n")
    f.write("bread\n")

with open("notes.txt", encoding="utf-8") as f:
    text = f.read()
print(len(text), text.split())  # 11 ['milk', 'bread']

Let's go through the example line by line:

  1. open("notes.txt", "w", encoding="utf-8") opens the file for writing and returns a file object. The words as f give it a name.
  2. The write method writes a string as it is and adds no line break itself, so each string ends with \n.
  3. The second with opens the same file for reading, and the read method returns its whole content as one string.
  4. print prints the length and the words: split with no argument splits the string at line breaks too.

Inside a Python string, a line break is written with the two signs \n, but it is one character. So text holds 11 characters: the four letters of milk, the five letters of bread and two line breaks.

The with block

The with block closes the file when its body ends, even if an exception occurred in the body. Closing saves what was written to disk and frees the file for other programs.

It is like a notebook that someone always puts back in the drawer for you, even if you are called away mid-sentence. Without with, you would have to close the file by hand, and you might forget to.

Open modes

The second argument of open is the mode. It decides what to do with a file that does not exist and with a file that already exists:

ModeFile missingFile exists
"r" (the default)FileNotFoundErrorreads from the start
"w"creates iterases the content
"a"creates itappends to the end
"x"creates itFileExistsError

Mode "w" erases the file right at opening, not at the first write. Here the notebook analogy stops working: opening a notebook does not mean tearing out all its pages, yet "w" does exactly that. To add a line to the old ones, open the file in mode "a".

The argument encoding="utf-8" sets the encoding — the way characters are written as bytes. Without it, Python takes the system's encoding. Then Russian text written on one computer may be read wrongly on another.

Reading line by line

A file object is an iterable: a for loop gets lines from it one at a time, and each ends with \n. The strip method removes that character:

Python
with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip(), end=";")  # milk;bread;

The loop reads the file in parts, not as a whole. So it can walk even a file larger than the memory: the whole file never sits in memory at once.

Common mistake

The program was started from another folder, and the file was not found:

Python
with open("notes.txt", encoding="utf-8") as f:  # ✗
    print(f.read())
TEXT
FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'

The interpreter counts the path "notes.txt" from the current folder — where the command was started, not where the program lies. Start the program from the file's folder or give the full path to the file.

Key points

  • open returns a file object, and with closes the file at the end of the block, even on an exception.
  • Mode "w" erases the file at opening, "a" appends to the end, "r" reads.
  • Write encoding="utf-8" so the text reads the same on any computer.
  • A for loop over a file gets lines one at a time, each ending with \n.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way