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:
- only to read it,
- to tear out every page and write from the beginning,
- to write on the empty line at the end,
- as a new book, which is refused if that book already exists.
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
open(file_name, mode, encoding=...)opens the file and returns a file object. Mode"r"means read. It is the default mode, so you may leave it out.encoding="utf-8"tells Python how letters are stored as bytes (the units of data in a file). Without it, Python 3.14 and older use the operating system's default encoding, and on Windows that default may not be UTF-8. Since Python 3.15, the default is UTF-8 on every system. Still always writeencoding="utf-8", so the result is the same on every computer and every Python version.with ... as f:is the context manager from the previous lesson:fholds the opened file, and the file is closed automatically as soon as the block ends.for line in f:reads one line on each pass of the loop. Each line carries the new-line character at its end,\n. So the first line is really'coffee with milk,3\n'..strip()removes that\n.
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:
f.read()reads the whole contents as one string:'coffee with milk,3\nsweet tea,4\ntoast,2\n'.f.readlines()reads the whole contents as a list, one line per item:['coffee with milk,3\n', 'sweet tea,4\n', 'toast,2\n'].
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.
f.write(text)does not add a new line by itself.f.write("iced orange,1")thenf.write("coffee with milk,2")gives one line,iced orange,1coffee with milk,2. Write the\nyourself at the end of the text.writeonly accepts a string.f.write(8)fails withTypeError: write() argument must be str, not int. Convert the number first withstr(8).
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
csvis a module that comes with Python.csv.DictReader(f)uses the first line as keys, so every line after it becomes a dictionary.csv.reader(f)gives every line as a plain list, including the header line:['item', 'quantity', 'price'], then['coffee with milk', '3', '15'], and so on.- Every value is a string. On the coffee with milk row,
row["quantity"] * 2gives'33', not6. Convert withint()before you calculate. Withint(), the total is 89: today's sales. - The Python documentation recommends
newline=""for CSV files, because thecsvmodule handles line endings itself.
📌 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
- Using mode
"w"to add. The old contents are gone immediately. To add at the end, use"a". \nmissing or carried along.write()adds no new line, and a line that was read still carries its\n. Write the\nyourself when writing, and use.strip()when reading.- Reading outside the
withblock. The result isValueError: I/O operation on closed file.Move that code inside the block. FileNotFoundErrorthough the file is there. Python looks for a name like"sales.txt"in the folder where you runpython3, not in the folder of your program file. Runpython3from the folder that holdssales.txt, or write that file's full address.
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.