Choose Text and Binary File Modes
Core idea
Choose a mode before opening a file: r reads, w creates or truncates, a appends and x creates only if absent. Text mode returns str and translates newlines according to newline; binary mode returns bytes. Specify encoding for text interchange. Use with to close owned files. In these examples TemporaryDirectory creates a disposable folder; Path(folder) / name constructs a child path, and p.open is the path-based equivalent of open(p, ...). Both helpers are covered later in this chapter.
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "note.txt" with p.open("w", encoding="utf-8") as f: f.write("سلام") with p.open("r", encoding="utf-8") as f: print(len(f.read())) with p.open("rb") as f: print(len(f.read()))Four code points occupy eight UTF-8 bytes.
Append without truncating
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "log.txt" with p.open("w", encoding="utf-8") as f: f.write("A") with p.open("a", encoding="utf-8") as f: f.write("B") print(p.read_text(encoding="utf-8"))Append preserves the earlier content.
Common mistake
Opening an existing file in w truncates it immediately. Do not supply encoding in binary mode. Use x when replacing an existing file is unacceptable.
Practice
Create a temporary file with x, then try x again and catch FileExistsError.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
File modes
Check your understanding of text and binary file modes.
What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "a" p.write_bytes(b"abc") with p.open("rb") as f: print(type(f.read()).__name__)What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "a" p.write_text("old", encoding="utf-8") with p.open("w", encoding="utf-8") as f: pass print(p.stat().st_size)Which mode refuses to overwrite an existing file?
Where is encoding appropriate?