diskshop.txt1with open("shop.txt", "w") as f:2 f.write("milk\n")3 f.write("eggs\n")4with open("shop.txt") as f:5 for line in f:6 print(line.strip())with open("todo.txt") as f:FileNotFoundError"w""milk\n""eggs\n"'milk\neggs\n'shop.txt'milk\n'milk'eggs\n'
Code card: files.py; the highlighted line is the one runningDisk: the file shop.txt and its size in bytesTerminal: where print() writesMemory boxes: the file object f (with its buffer) and the variable linefiles.py writes a two-line shopping list to shop.txt and reads it back. Each step lights the parts it is about. The two writes collect in the file object's buffer while the file on disk stays at 0 bytes; closing at the end of the with block carries all 10 characters to the disk. Reading opens the file again, and each turn of the for loop carries one line into the variable line, which print() shows without its newline. In the last step line 4 asks for todo.txt, which does not exist, and Python stops with FileNotFoundError.

Writing a file

  1. Variables live in memory and vanish when a program ends. A file is data saved on disk under a name, such as shop.txt, so it is still there next time. This program writes a shopping list, then reads it back.

Reading it back

When it fails

Try it yourself

;; step 1/10
# a variable is gone when the program ends:
items = ["milk", "eggs"]

# a file stays on disk; this program makes one:
$ python files.py
milk
eggs
$ ls shop.txt
shop.txt

File objects are buffered: small writes wait in memory until the buffer fills, you call f.flush(), or the file is closed. The Python tutorial warns that without with or f.close(), what you wrote might not all reach the disk, even if the program ends normally. The figure shortens the error. The real message shows the full path to files.py, then line 4 itself with ^ marks under the call, and prints the last line in one piece; a narrow terminal wraps it.