Sub topic 8
Reading and Writing Files with Path Methods
This chapter assumes you can build and inspect Path objects (the / operator, name, suffix, parent) and that you know how to check exists(), is_file(), and is_dir(). It also assumes you know the difference between text and bytes in Python. Here you will use Path objects to move data in and out of files.
Two levels of API
Path gives you two ways to work with file contents:
- One-shot methods read or write a whole file in a single call:
read_text(),write_text(),read_bytes(), andwrite_bytes(). Each one opens the file, does the work, and closes it. Path.open()returns a file object, just like the built-inopen(). Use it when you need to append, stream line by line, or control the mode yourself.
Reading and writing text
write_text() creates the file if it does not exist and replaces its contents if it does. It returns the number of characters written. read_text() returns the full contents as one string.
from pathlib import Path
config = Path("settings.txt")
count = config.write_text("mode=fast\nretries=3\n", encoding="utf-8")
print(count) # 20
content = config.read_text(encoding="utf-8")
print(content.splitlines()) # ['mode=fast', 'retries=3']splitlines() is the usual way to turn the result into a list of lines. It removes the line endings, which read_text() leaves in place.
Always pass `encoding`
If you omit encoding, Python uses the platform's default. On many Windows machines that is a legacy code page such than UTF-8, so the same program can write a file on one machine that it cannot read on another. Pass encoding="utf-8" explicitly unless you know the file uses something else.
The errors argument controls what happens with bytes that are not valid in the chosen encoding:
from pathlib import Path
raw = Path("mixed.bin")
raw.write_bytes(b"caf\xc3\xa9 \xff") # the final byte is not valid UTF-8
print(raw.read_text(encoding="utf-8", errors="replace")) # café �The default, errors="strict", raises UnicodeDecodeError. Use "replace" for display-only work, and keep "strict" when silent data damage would be worse than a crash.
Line endings
write_text() accepts a newline argument since Python 3.10. With the default, any "\n" in your string is translated to the platform's line separator ("\r\n" on Windows). Pass newline="\n" when you need identical bytes on every platform, for example for files that are checked into version control.
from pathlib import Path
Path("unix_style.txt").write_text("a\nb\n", encoding="utf-8", newline="\n")Reading and writing bytes
Binary data such as images, archives, and serialized objects must not go through text decoding. Use the bytes methods, which take no encoding:
from pathlib import Path
blob = Path("payload.bin")
written = blob.write_bytes(bytes([0, 1, 2, 255]))
print(written) # 4
print(blob.read_bytes()) # b'\x00\x01\x02\xff'
print(blob.stat().st_size) # 4Copying a small file is therefore dst.write_bytes(src.read_bytes()). For large files, use shutil.copyfile() instead. It copies in chunks and does not hold the whole file in memory.
Using `Path.open()`
Path.open() takes the same arguments as the built-in open(), minus the path. Always use it in a with block so the file closes even when an error occurs.
Appending
write_text() always replaces the file. To add to the end, open in append mode:
from pathlib import Path
log = Path("events.log")
log.write_text("", encoding="utf-8") # start empty for this demo
for event in ("start", "work", "stop"):
with log.open("a", encoding="utf-8") as f:
f.write(event + "\n")
print(log.read_text(encoding="utf-8").splitlines()) # ['start', 'work', 'stop']Streaming lines
read_text() loads everything at once. For a large log file, iterate over the file object, which reads one line at a time:
from pathlib import Path
log = Path("events.log")
with log.open("r", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.rstrip("\n"))Refusing to overwrite
Mode "x" creates the file and raises FileExistsError if it already exists. This avoids a race between checking exists() and writing, because the operating system does both steps as one action.
from pathlib import Path
lock = Path("job.lock")
lock.unlink(missing_ok=True) # clean up from earlier runs
with lock.open("x", encoding="utf-8") as f:
f.write("owned by this process\n")
try:
with lock.open("x", encoding="utf-8") as f:
f.write("second writer\n")
except FileExistsError:
print("lock already held") # lock already heldModes at a glance
| Mode | Meaning | Creates file | Existing content |
|---|---|---|---|
| `"r"` | Read text (default) | No, raises `FileNotFoundError` | Kept |
| `"w"` | Write text | Yes | Erased immediately |
| `"a"` | Append text | Yes | Kept, new data goes at the end |
| `"x"` | Exclusive create | Yes, or raises `FileExistsError` | Not applicable |
| `"rb"`, `"wb"`, `"ab"` | Same as above, in bytes | As above | As above |
Creating an empty file
Path.touch() creates an empty file, or updates the modification time if the file already exists. It is the pathlib equivalent of the Unix touch command.
from pathlib import Path
marker = Path("done.flag")
marker.touch(exist_ok=True)
print(marker.exists()) # TrueWith the default exist_ok=True, an existing file is left alone apart from its timestamps. With exist_ok=False, an existing file raises FileExistsError.
Errors you will meet
These exceptions come up most often when reading and writing:
FileNotFoundError: for reading, the file is missing. For writing, the parent directory is missing.write_text()does not create directories.IsADirectoryError: the path names a directory, not a file.NotADirectoryError: a component in the middle of the path is a file.PermissionError: the process lacks the needed rights.UnicodeDecodeError: the bytes do not match the encoding you chose.
The most common mistake is writing into a folder that does not exist yet. Create the parent first, as covered in the earlier chapter on directories:
from pathlib import Path
target = Path("build") / "reports" / "summary.txt"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("ok\n", encoding="utf-8")
print(target.read_text(encoding="utf-8"), end="") # okTo handle a missing file without a separate exists() check, catch the exception. Between the check and the read, another process could delete the file, so the try form is the more reliable one:
from pathlib import Path
def read_or_default(path: Path, default: str = "") -> str:
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return default
print(repr(read_or_default(Path("does_not_exist.txt"), "n/a"))) # 'n/a'Writing safely: replace the file in one step
write_text() truncates the target before writing. If the program crashes midway, you are left with a partial or empty file. A safer pattern is to write a temporary file in the same directory, then swap it in with Path.replace(). On the same file system, the replacement is a single operation, so readers see either the old file or the new one.
from pathlib import Path
def atomic_write_text(path: Path, text: str, encoding: str = "utf-8") -> None:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(text, encoding=encoding)
tmp.replace(path)
atomic_write_text(Path("state") / "current.json", '{"step": 1}\n')
print(Path("state/current.json").read_text(encoding="utf-8"), end="") # {"step": 1}The temporary file must live in the same directory as the target. If it were on another file system, the replace would become a copy and lose its all-or-nothing behavior. This sketch does not call fsync, so it protects against a crash of your program but not against power loss.
Reading structured data
read_text() combines well with the standard library parsers. The path object stays the single source of truth for where the data lives:
import json
from pathlib import Path
data_file = Path("scores.json")
data_file.write_text(json.dumps({"ana": 12, "li": 9}), encoding="utf-8")
scores = json.loads(data_file.read_text(encoding="utf-8"))
print(max(scores, key=scores.get)) # anaMany libraries also accept path objects directly. json.load needs an open file, but open() on a Path works anywhere a path-like value is allowed, so with data_file.open(encoding="utf-8") as f: json.load(f) is an equal choice.
Summary of trade-offs
| Need | Use | Watch out for |
|---|---|---|
| Read a small text file | `read_text(encoding=...)` | Loads everything into memory |
| Replace a small text file | `write_text(..., encoding=...)` | Truncates first, not crash-safe |
| Binary data | `read_bytes()` / `write_bytes()` | No encoding involved |
| Append or stream | `open("a")` / iterate file object | Use `with` to close the file |
| Never overwrite | `open("x")` | Raises `FileExistsError` |
| Crash-safe replace | temp file + `replace()` | Keep temp file in the same directory |
Exercise
Write a function append_unique(path, line) that appends line to a text file only if no existing line equals it. The file may not exist yet, and its parent directory may be missing. Use UTF-8. What does your function do in each case?
Show answer
A correct solution: from pathlib import Path def appendunique(path, line): path = Path(path) path.parent.mkdir(parents=True, existok=True) try: existing = path.readtext(encoding="utf-8").splitlines() except FileNotFoundError: existing = [] if line in existing: return False with path.open("a", encoding="utf-8") as f: f.write(line + "\n") return True The parent is created first, so a missing directory does not raise. A missing file is treated as having no lines, and append mode creates it. A duplicate line returns False without touching the file. The function writes with "a" rather than writetext(), so earlier lines are never erased.
Exercise
A script calls Path("out/result.txt").write_text(report, encoding="utf-8") and fails with FileNotFoundError, although result.txt was never expected to exist beforehand. What is wrong, and how do you fix it?
Show answer
The directory out does not exist, so the file cannot be created in it. writetext() creates the file but not its parent directories. Fix it by calling Path("out").mkdir(parents=True, existok=True) before writing, or by using target.parent.mkdir(parents=True, exist_ok=True) on the full target path.