Sub topic 8
Reading and writing files with Path methods
This chapter assumes you can build Path objects, check whether a path exists with exists() and is_file(), and handle basic Python exceptions. Here you will read and write whole files, and open files for streaming, using methods on the path itself.
Whole-file helpers
A Path has four methods that open a file, do one operation, and close it. You don't need a with block.
| Method | Reads or writes | Returns |
|---|---|---|
| `read_text()` | text | `str` |
| `write_text(data)` | text | number of characters written |
| `read_bytes()` | bytes | `bytes` |
| `write_bytes(data)` | bytes | number of bytes written |
from pathlib import Path
out_dir = Path("output")
out_dir.mkdir(parents=True, exist_ok=True)
note = out_dir / "hello.txt"
count = note.write_text("hello\nworld\n", encoding="utf-8")
print(count) # 12
print(note.read_text(encoding="utf-8"))
blob = out_dir / "data.bin"
blob.write_bytes(bytes([0, 1, 2, 255]))
print(list(blob.read_bytes())) # [0, 1, 2, 255]Always pass encoding for text. If you omit it, Python uses the platform's default, and the same program can then behave differently on Windows and Linux. Pass encoding="utf-8" unless you know the file uses something else.
What the helpers do to existing files
write_text() and write_bytes() open the file in write mode. That mode truncates the file, so the old content is gone before the new content is written. The methods also don't create missing parent directories.
from pathlib import Path
target = Path("output") / "reports" / "today.txt"
target.parent.mkdir(parents=True, exist_ok=True) # create the folder first
target.write_text("first\n", encoding="utf-8")
target.write_text("second\n", encoding="utf-8") # replaces "first"
print(target.read_text(encoding="utf-8")) # secondOpening a file for more control
Use Path.open() when you need appending, line-by-line reading, or a mode the helpers don't offer. It takes the same arguments as the built-in open(), and you should use it in a with block.
from pathlib import Path
log = Path("output") / "app.log"
log.parent.mkdir(parents=True, exist_ok=True)
with log.open("a", encoding="utf-8") as f: # "a" appends
f.write("started\n")
f.write("finished\n")
with log.open("r", encoding="utf-8") as f:
for line in f: # one line at a time
print(line.rstrip("\n"))Iterating over the file object keeps only one line in memory. read_text() loads the whole file, so it is a poor choice for a multi-gigabyte log.
Common errors
- FileNotFoundError on read. The file doesn't exist, or the relative path is resolved against a different working directory than you expected. Print
path.resolve()to see what Python is using. - FileNotFoundError on write. The parent directory is missing. Call
path.parent.mkdir(parents=True, exist_ok=True)first. - IsADirectoryError. The path points to a directory. Check with
is_file()if the input is not under your control. - UnicodeDecodeError. The file isn't valid in the encoding you named. Confirm the real encoding, or use
read_bytes()and decode yourself. - TypeError on write.
write_text()accepts onlystr, andwrite_bytes()accepts only bytes-like objects. Convert numbers withstr()before writing.
from pathlib import Path
config = Path("missing.cfg")
try:
text = config.read_text(encoding="utf-8")
except FileNotFoundError:
text = "" # fall back to a default
print(repr(text))Catching the exception is more reliable than testing exists() first. The file can disappear between the check and the read.
Exercise
You run Path("reports/2026/summary.txt").write_text("done", encoding="utf-8") and get FileNotFoundError, although you are not reading anything. What is the likely cause, and what one line fixes it?
Show answer
The directories reports/2026 do not exist, and write_text() does not create parent directories. Add Path("reports/2026/summary.txt").parent.mkdir(parents=True, exist_ok=True) before the write.
Exercise
Which method would you use to add one line to the end of an existing log file without erasing its content, and why not write_text()?
Show answer
Use path.open("a", encoding="utf-8") in a with block and call write(). write_text() opens the file in write mode and truncates it, so the earlier content would be lost.