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:
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:
open("notes.txt", "w", encoding="utf-8")opens the file for writing and returns a file object. The wordsas fgive it a name.- The
writemethod writes a string as it is and adds no line break itself, so each string ends with\n. - The second
withopens the same file for reading, and thereadmethod returns its whole content as one string. printprints the length and the words:splitwith 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:
| Mode | File missing | File exists |
|---|---|---|
"r" (the default) | FileNotFoundError | reads from the start |
"w" | creates it | erases the content |
"a" | creates it | appends to the end |
"x" | creates it | FileExistsError |
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:
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:
with open("notes.txt", encoding="utf-8") as f: # ✗
print(f.read())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
openreturns a file object, andwithcloses 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
forloop 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.