Sub topic 8
One-call reads and writes with pathlib
This chapter assumes you can build a Path object, know what open() returns, and understand the with statement and text encodings from earlier chapters. It covers the four Path methods that read or write a whole file in one call, and when to use them instead of open().
The four shortcuts
A Path object has four methods that open the file, do one operation, and close it for you:
| Method | Returns | Mode used internally |
|---|---|---|
| `read_text(encoding=...)` | `str` | `"r"` |
| `write_text(data, encoding=...)` | number of characters written | `"w"` |
| `read_bytes()` | `bytes` | `"rb"` |
| `write_bytes(data)` | number of bytes written | `"wb"` |
Each method hides a with block. You get the same guarantee that the file is closed, with no file object to manage.
from pathlib import Path
path = Path("data") / "greeting.txt"
path.parent.mkdir(parents=True, exist_ok=True)
count = path.write_text("h\u00e9llo\n", encoding="utf-8")
print(count)
print(path.read_text(encoding="utf-8"))This prints 6 and then the text héllo. The count is characters, not bytes. In UTF-8 the file holds 7 bytes, because é takes two.
Always pass the encoding
read_text() and write_text() use the platform's default encoding when you leave encoding out. That default differs between systems, so a file written on one machine can fail to decode on another. Pass encoding="utf-8" every time, as you do with open().
from pathlib import Path
raw = Path("data/greeting.txt").read_bytes()
print(raw)
print(raw.decode("utf-8") == Path("data/greeting.txt").read_text(encoding="utf-8"))The output is b'h\xc3\xa9llo\n' and then True. This shows that read_text is read_bytes plus a decode step.
What the shortcuts do not do
The shortcuts are deliberately simple. Four limits cause most mistakes:
- They overwrite.
write_textalways opens in"w"mode, which truncates an existing file. There is no append option. - They load everything.
read_textreturns the whole file as one string. For a multi-gigabyte log, iterate withopen()instead. - They do not create directories. If
data/is missing,write_textraisesFileNotFoundError. Callpath.parent.mkdir(parents=True, exist_ok=True)first. - They are not atomic. A crash in the middle of
write_textcan leave a half-written file. A later chapter covers the temporary-file pattern.
For appending, or for any case that needs a file object, use Path.open(). It takes the same arguments as the built-in open().
from pathlib import Path
log = Path("data") / "events.log"
with log.open("a", encoding="utf-8") as f:
f.write("started\n")Choosing between them
Small configuration files, templates, and short JSON documents suit the shortcuts well. Pass the string you read to json.loads(), or write the output of json.dumps().
import json
from pathlib import Path
config_path = Path("config.json")
config_path.write_text(json.dumps({"debug": True}, indent=2), encoding="utf-8")
config = json.loads(config_path.read_text(encoding="utf-8"))
print(config["debug"])Common errors
The shortcuts raise the same exceptions as open(). A missing file gives FileNotFoundError, and a file you cannot read gives PermissionError. A file that is not valid in the encoding you named gives UnicodeDecodeError. Wrap the call in try/except as you would for open().
from pathlib import Path
try:
text = Path("missing.txt").read_text(encoding="utf-8")
except FileNotFoundError:
text = ""Exercise
You need to add one line to the end of an existing log file with pathlib. Why does Path("app.log").write_text("done\n", encoding="utf-8") not do this, and what should you write instead?
Show answer
write_text opens the file in "w" mode, so it truncates the file and leaves only "done\n". Use with Path("app.log").open("a", encoding="utf-8") as f: f.write("done\n"), which opens in append mode and keeps the existing content.