File I/O — Python

with open("sales.txt", "r", encoding="utf-8") as f: opens a file and closes it automatically at the end of the block. Reading after the block gives…

Mr. Darto's cashier program adds up a whole day of sales: 3 coffee with milk, 4 sweet tea, 2 toast. Then the terminal is closed, and all those numbers are gone. Variables only exist while the program runs.

The only thing still there tomorrow morning is what was saved in a file, because a file stays on the disk (the computer's storage). File I/O (input/output) means reading what is in a file and writing to a file.

A file is like the sales book on the stall's shelf. Every time someone uses the book, they take it from the shelf and open it in one of four ways:

In Python the book is the file, and the way of opening it is called the mode. with makes sure the file is closed again after use, like the book going back on the shelf.

Reading a file

These are the contents of sales.txt, which is in the same folder as stall.py:

coffee with milk,3
sweet tea,4
toast,2

This code reads that file line by line:

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

The output:

coffee with milk,3
sweet tea,4
toast,2

Without .strip(), print(line) prints the line's own \n, then adds the new line from print itself. The result is an empty line between the lines:

coffee with milk,3

sweet tea,4

toast,2

There are two other ways to read:

Four ways to open a file

The four ways of opening the sales book at the start of this lesson are these four modes, in the same order:

Mode Meaning If the file exists If it does not
"r" read read from the start FileNotFoundError: [Errno 2] No such file or directory: 'sales.txt'
"w" rewrite emptied first, then written created
"a" add at the end (append) old contents stay, new text at the end created
"x" make a new one FileExistsError: [Errno 17] File exists: 'sales.txt' created

Mr. Darto records one glass of iced orange with mode "a":

with open("sales.txt", "a", encoding="utf-8") as f:
    f.write("iced orange,1\n")

Run it, then look at the file's contents:

$ python3 stall.py
$ cat sales.txt
coffee with milk,3
sweet tea,4
toast,2
iced orange,1

(cat is the terminal command that shows a file's contents. On Windows it is type.) The line iced orange,1 is added at the end, and the three old lines are still there.

If the same code uses mode "w", cat shows only one line: iced orange,1. The three old lines are gone as soon as the file is opened, even before write runs. Combined modes such as "r+" (read and write without emptying) also exist, but you rarely need them.

The file is closed after with

This code reads the first line inside with, then tries to read the rest outside the block:

with open("sales.txt", encoding="utf-8") as f:
    first_line = f.readline()
print(first_line.strip())
the_rest = f.read()

The first line prints, then the program fails:

coffee with milk,3
Traceback (most recent call last):
  File "/home/darto/stall.py", line 4, in <module>
    the_rest = f.read()
ValueError: I/O operation on closed file.

The variable f still exists, but with closed the file at the end of the block (f.closed is True). All code that reads or writes the file has to be inside the with block. Closing a file is important: what you write is only guaranteed to be saved to the disk after the file is closed.

CSV: a file that holds a table

CSV (comma-separated values) is a table in plain text. Each line of text is one row of the table, the columns are separated by commas, and the first line usually holds the column names. These are the contents of sales.csv:

item,quantity,price
coffee with milk,3,15
sweet tea,4,5
toast,2,12

This code reads every line, then adds up the total sales:

import csv

total = 0
with open("sales.csv", encoding="utf-8", newline="") as f:
    for row in csv.DictReader(f):
        print(row)
        total += int(row["quantity"]) * int(row["price"])
print(total)

The output:

{'item': 'coffee with milk', 'quantity': '3', 'price': '15'}
{'item': 'sweet tea', 'quantity': '4', 'price': '5'}
{'item': 'toast', 'quantity': '2', 'price': '12'}
89

📌 pathlib: a file's address as an object

Path from the pathlib module is an object that holds a file's address (the file's name and its folder):

from pathlib import Path

p = Path("sales.txt")
print(p.exists())                                  # True
print(p.name, p.suffix)                            # sales.txt .txt
print(p.read_text(encoding="utf-8").splitlines())  # ['coffee with milk,3', 'sweet tea,4', 'toast,2']
print(Path("report.txt").exists())                 # False

exists() checks whether the file is there, before you open it. read_text() opens, reads and closes the file in one call. write_text(text) does the opposite: it writes text to the file. Like mode "w", this method overwrites the old contents.

⚠️ File contents that vanish, and files that can't be found

TL;DR: with open("sales.txt", "r", encoding="utf-8") as f: opens a file and closes it automatically at the end of the block. Reading after the block gives ValueError: I/O operation on closed file. There are four modes, which are ways of opening a file. "r" reads (the file must exist, otherwise you get FileNotFoundError) and "w" empties the file, then writes. "a" adds at the end without deleting the old contents, and "x" makes a new file (if it already exists, you get FileExistsError). for line in f: reads line by line, and each line carries \n (the new-line character), so use .strip(). write() only accepts a string and adds no \n. Always write encoding="utf-8". csv.DictReader reads a CSV (a table in plain text, with commas between the columns) as one dictionary per line, and every value is a string, so convert with int() before calculating. Path("...").exists() checks whether a file is there before you open it.

⚡ Read line by line

Write:

with open("sales.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
Guess first: if .strip() is removed, what changes?

A blank line appears between every line. Each line that's read carries a \n (the new-line character) at its end, then print adds another new line.

Meaning: open() opens the file, and with closes it automatically at the end of the block. for line in f: reads one line on each pass of the loop. Always write encoding="utf-8", so the result is the same on every computer.

⚡ The mode decides what happens to the old contents

Write:

with open("sales.txt", "a", encoding="utf-8") as f:
    f.write("iced orange,1\n")
Guess first: mode "a" in this code adds text at the end of the file. If the mode is changed to "w" (rewrite), what's left in the file?

Only iced orange,1. All the old lines are gone as soon as the file is opened, before write even runs.

Meaning: The mode is the way a file is opened, written after the file name in open(). "r" reads, "w" empties then writes, "a" adds at the end without deleting the old contents, "x" makes a new file. To add one line, use "a".

⚡ write adds no new line

Meaning: f.write() doesn't add a new line (\n) by itself, so put \n at the end of the text. write also only accepts a string, so convert a number with str() first.

⚡ CSV: a table in plain text

Meaning: CSV is a table in plain text: commas separate the columns, and the first line holds the column names. csv.DictReader(f) uses that first line as the keys, so each line after it becomes a dictionary. Every value is a string: for a quantity of 3, row["quantity"] * 2 gives '33', not 6. Convert with int() before calculating.

What you will learn