Sub topic 8
One-call reads and writes with pathlib
This chapter covers the four Path methods that read or write a whole file in one call: read_text, write_text, read_bytes, and write_bytes. It assumes you can use open() with with, you know the difference between str and bytes, you can build a Path with the / operator, and you can write a basic try/except.
What the shortcuts replace
Reading a whole file with open() takes a with block, a mode, an encoding, and a read() call. A Path object wraps that sequence in one method:
from pathlib import Path
path = Path("data") / "greeting.txt"
path.parent.mkdir(parents=True, exist_ok=True)
written = path.write_text("h\u00e9llo\n", encoding="utf-8")
print(written)
text = path.read_text(encoding="utf-8")
print(repr(text))This prints 6, then 'héllo\n'. Each method opens the file, does one operation, and closes the file before it returns. You never hold a file object, so there is nothing to forget to close.
| Method | Mode used inside | Returns | Typical use |
|---|---|---|---|
| `read_text(encoding=None, errors=None)` | `"r"` | `str` | Config files, small logs, templates |
| `write_text(data, encoding=None, errors=None, newline=None)` | `"w"` | number of characters written | Generated reports, small outputs |
| `read_bytes()` | `"rb"` | `bytes` | Small images, hashing, parsing a binary header |
| `write_bytes(data)` | `"wb"` | number of bytes written | Saving downloaded or generated binary data |
The newline argument of write_text needs Python 3.10 or later. read_text gained its own newline argument in Python 3.13.
Text methods
Always pass an encoding
If you omit encoding, Python uses the platform's default. That default is often UTF-8 on Linux and macOS. On Windows it can be a legacy code page such as cp1252. A script that works on your laptop can then corrupt or reject the same file elsewhere. Pass encoding="utf-8" unless you have a reason not to. This is the same rule as with open().
You can check the effect directly by looking at the bytes:
from pathlib import Path
path = Path("accent.txt")
path.write_text("h\u00e9llo\n", encoding="utf-8")
raw = path.read_bytes()
print(raw)
print(len(raw))The output is b'h\xc3\xa9llo\n' and 7. The text has 6 characters but the file has 7 bytes, because UTF-8 stores é in two bytes. write_text returns the character count (6), and write_bytes returns the byte count.
What `write_text` does to existing files
write_text opens the file in "w" mode. If the file exists, it is truncated to zero length before your data is written. If the file does not exist, it is created, but its parent directory must already exist. When it does not, you get FileNotFoundError. That is why the first example calls path.parent.mkdir(parents=True, exist_ok=True) first.
There is no append variant. To append, go back to Path.open, which accepts the same arguments as the built-in open():
from pathlib import Path
log = Path("app.log")
with log.open("a", encoding="utf-8") as f:
f.write("started\n")Do not emulate append with p.write_text(p.read_text() + "new line"). It reads and rewrites the whole file for each addition. If another process appends between your read and your write, you silently erase its line.
Newline translation
Text methods use universal newlines, as open() does in text mode. When reading, \r\n and \r become \n. When writing, \n becomes the platform's line separator, which is \r\n on Windows. This is why a file written on Windows can have different bytes from the same call on Linux.
On Python 3.10 and later you can control the output:
from pathlib import Path
out = Path("unix_style.txt")
out.write_text("one\ntwo\n", encoding="utf-8", newline="\n")
print(out.read_bytes())This prints b'one\ntwo\n' on every platform. Use newline="\n" when a file must be byte-identical across systems, for example a file you commit to version control or checksum.
Decoding errors
If the file contains bytes that are not valid in the chosen encoding, read_text raises UnicodeDecodeError. The errors argument changes that behavior:
from pathlib import Path
path = Path("mixed.bin")
path.write_bytes(b"caf\xe9 au lait\n")
try:
path.read_text(encoding="utf-8")
except UnicodeDecodeError as exc:
print("strict failed:", exc.reason)
print(path.read_text(encoding="utf-8", errors="replace"))
print(path.read_text(encoding="latin-1"))The byte \xe9 is é in Latin-1 but is not valid UTF-8 on its own. With errors="replace", the bad byte becomes the replacement character \ufffd. This is fine for display, but it loses data. If you will write the text back, the original byte is gone. Prefer fixing the encoding. Use errors="replace" or errors="ignore" only when losing information is acceptable.
Choosing between text and bytes
Pick the method by what the file contains, not by how you plan to process it.
The first question matters most. All four methods load or hold the entire content in memory at once. read_text on a 4 GB log builds a 4 GB string, and possibly more while decoding. For large files, use path.open() and iterate over lines, or read in chunks, as covered in earlier chapters.
Patterns that fit one call
Small structured files
json pairs naturally with the shortcuts, because json.loads and json.dumps work on strings:
import json
from pathlib import Path
config_path = Path("config.json")
config_path.write_text(
json.dumps({"retries": 3, "verbose": True}, indent=2),
encoding="utf-8",
)
config = json.loads(config_path.read_text(encoding="utf-8"))
config["retries"] += 1
config_path.write_text(json.dumps(config, indent=2), encoding="utf-8")
print(config)This prints {'retries': 4, 'verbose': True}. For CSV, stay with open(..., newline=""). The csv module needs a file object and manages line endings itself.
Splitting into lines
read_text().splitlines() gives a list of lines without their trailing newlines:
from pathlib import Path
path = Path("names.txt")
path.write_text("Ada\nLinus\nGrace\n", encoding="utf-8")
names = path.read_text(encoding="utf-8").splitlines()
print(names)The result is ['Ada', 'Linus', 'Grace']. Note that splitlines() splits on more than \n. It also splits on \r, \x0b, \x0c, \x1c to \x1e, \x85, \u2028, and \u2029. If a data field might contain one of those characters, use split("\n") instead. That leaves a final empty string when the file ends with a newline.
Copying and transforming small files
Because read_bytes and write_bytes do no decoding or newline translation, they copy a small file exactly:
from pathlib import Path
src = Path("input.bin")
src.write_bytes(bytes(range(16)))
dst = Path("copy.bin")
dst.write_bytes(src.read_bytes())
print(dst.read_bytes() == src.read_bytes())This prints True. For files that might be large, copy in chunks as shown in the binary files chapter, or use shutil.copyfile.
Gotchas and failure modes
Errors come from the call itself
Because there is no separate open() step, the same call can raise errors from opening, reading, decoding, and writing. The common ones:
FileNotFoundError: the file does not exist when reading, or the parent directory does not exist when writing.PermissionError: you lack read or write permission.IsADirectoryError: the path is a directory. On Windows this usually appears asPermissionErrorinstead.UnicodeDecodeErrorandUnicodeEncodeError: the content does not fit the chosen encoding.
from pathlib import Path
settings = Path("settings.txt")
try:
text = settings.read_text(encoding="utf-8")
except FileNotFoundError:
text = ""
except UnicodeDecodeError:
print("settings.txt is not valid UTF-8")
raiseWrap only the shortcut call in the try block, so unrelated bugs are not caught by accident.
Truncation happens before your data is written
write_text empties the file as soon as it opens it. Suppose the encoding step fails, for example write_text("snowman \u2603", encoding="ascii") raises UnicodeEncodeError. Python encodes as it writes, so the file may already be truncated or partly written. The same applies if the process is killed mid-write or the disk fills up. A read-modify-write cycle with write_text on your only copy of a file is therefore risky:
from pathlib import Path
path = Path("counter.txt")
path.write_text("0", encoding="utf-8")
value = int(path.read_text(encoding="utf-8"))
path.write_text(str(value + 1), encoding="utf-8")
print(path.read_text(encoding="utf-8"))For a throwaway script this is fine. For data you cannot regenerate, use the temporary-file technique from the safe-writes chapter, which replaces the file in one step.
Not safe for concurrent writers
Two processes calling write_text on the same path can interleave or overwrite each other. The shortcuts offer no locking. Use one writer per file, or coordinate with a lock or a database.
The path might not be what you expect
Relative paths resolve against the current working directory, not the script's location. When a file must sit next to your script, anchor the path:
from pathlib import Path
here = Path(__file__).resolve().parent
template = (here / "template.txt").read_text(encoding="utf-8")__file__ is undefined in an interactive session, so this snippet only works when saved as a script.
Exercises
Exercise
What does Path("notes.txt").write_text("a\nb\n", encoding="utf-8") return, and what happens if notes.txt already contains text?
Show answer
It returns 4, the number of characters written ("a", newline, "b", newline). The existing content is discarded, because the method opens the file in "w" mode, which truncates it before writing.
Exercise
You want to add one line to the end of events.log without reading the existing content. Why is write_text the wrong tool, and what should you use?
Show answer
write_text always truncates and replaces the file, and there is no append option. Use Path("events.log").open("a", encoding="utf-8") in a with block and call write on the file object.
Exercise
Write a function count_lines(path) that returns the number of lines in a small UTF-8 text file using one pathlib call, and returns 0 if the file does not exist.
Show answer
from pathlib import Path def countlines(path): try: text = Path(path).readtext(encoding="utf-8") except FileNotFoundError: return 0 return len(text.splitlines())
Exercise
A 6-character string containing one é is written with write_text(..., encoding="utf-8"). How many bytes does the file hold, and what do read_bytes() and read_text(encoding="utf-8") give back?
Show answer
The file holds 7 bytes, because é takes two bytes in UTF-8. read_bytes() returns the raw 7 bytes. read_text(encoding="utf-8") returns the original 6-character string.