Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
The file modes you haven't met (x, r+, b), reading big files and the file position, pathlib for joining and searching paths, and what with really does: __enter__, __exit__, and your own context managers with contextlib.
What you will learn
- Use the x, r+ and rb modes and know when each one is right
- Read big files line by line or in chunks, and understand the file position
- Build, inspect and search paths with pathlib
- Explain what with does through __enter__ and __exit__, and write context managers with a class or @contextmanager
Before you start
- Reading and writing a file with open and with
- Python classes and try/finally
Almost every program you write will read a file or save one. So it needs to find that file, and close it properly, even when something fails. This article goes beyond reading and writing a file: more modes, reading strategies, paths, and what the with statement is really doing.
More file modes
You know r reads, w starts fresh and a adds to the end. Add three more: x only creates a brand new file, r+ reads and writes the same file, and b gives you raw bytes instead of text. There's also t for text, but it's the default, so plain r means rt. You can join them, so rb means read in binary.
Logs are opened with a, because w would wipe the earlier lines. Writing "[INFO] started" with w and then "[INFO] listening" with a leaves both lines in app.log.
x: create, but never overwrite
for attempt in (1, 2):
try:
with open("config.ini", "x") as f:
f.write("theme=dark\n")
print("attempt", attempt, "created it")
except FileExistsError:
print("attempt", attempt, "already exists")
attempt 1 created it
attempt 2 already exists
With w, that second attempt would have wiped your settings. Use x when overwriting would hurt.
r+: read and write one file
from pathlib import Path
Path("note.txt").write_text("hello world")
with open("note.txt", "r+") as f:
print(f.read(5))
f.write("!")
f.seek(0)
print(f.read())
hello
hello world!
You'd expect the "!" right after "hello", but it lands at the very end. Python reads ahead in chunks, so the file's position had already moved past the text. When you switch between reading and writing, call seek first so you know where you are.
b: bytes, not text
text = "caf\u00e9"
with open("menu.txt", "w", encoding="utf-8") as f:
f.write(text)
with open("menu.txt", "rb") as f:
raw = f.read()
print(raw)
print(len(text), len(raw))
print(raw.decode("utf-8") == text)
b'caf\xc3\xa9'
4 5
True
The b in front of the quote says these are bytes. The accented e takes two bytes, \xc3\xa9, so four characters become five bytes. Images, audio and zip files aren't text, so you open those with b.
Reading strategies
from pathlib import Path
Path("data.txt").write_text("one\ntwo\nthree\n")
with open("data.txt") as f:
print(repr(f.read()))
with open("data.txt") as f:
print(repr(f.readline()))
print(repr(f.readline()))
with open("data.txt") as f:
print(f.readlines())
'one\ntwo\nthree\n'
'one\n'
'two\n'
['one\n', 'two\n', 'three\n']
repr shows the new lines. read and readlines load the whole file into memory at once. That's fine for a small file, not for a huge log. For a big file, loop over the file object, or read in chunks:
from pathlib import Path
Path("data.txt").write_text("one\ntwo\nthree\n")
with open("data.txt") as f:
for line in f:
print(line.strip())
with open("data.txt") as f:
while chunk := f.read(4):
print(repr(chunk))
one
two
three
'one\n'
'two\n'
'thre'
'e\n'
The loop hands you one line at a time and lets go of the one before, so memory stays small. That while line with := stores the chunk and checks it in one go; an empty string stops the loop. One cut falls in the middle of "three", because chunks don't care about lines.
Every open file keeps a position
from pathlib import Path
Path("data.txt").write_text("one\ntwo\nthree\n")
with open("data.txt") as f:
print(f.tell())
f.readline()
print(f.tell())
print(repr(f.read()))
print(repr(f.read()))
f.seek(0)
print(repr(f.readline()))
0
5
'two\nthree\n'
''
'one\n'
Think of it as a bookmark. tell shows it. After one line it's 5: three letters plus the line ending, which takes two bytes on Windows (on Mac or Linux you'd see 4). A second read returns an empty string because the bookmark is at the end, and seek(0) moves it back. This is why a second read often seems to return nothing.
Paths with pathlib
A path is like a postal address, and you shouldn't glue the pieces by hand, because Windows and Linux use different slashes.
from pathlib import Path
report = Path("data") / "reports" / "sales.csv"
print(report.name)
print(report.stem)
print(report.suffix)
print(report.parent.as_posix())
print(report.parts)
print(report.with_suffix(".txt").name)
print(report.exists())
# os.path.join("data", "reports") is the older way
sales.csv
sales
.csv
data/reports
('data', 'reports', 'sales.csv')
sales.txt
False
The / operator joins pieces with the right slash for your system. exists() is False because a path is only a description until you touch the disk.
from pathlib import Path
out = Path("output") / "charts"
out.mkdir(parents=True, exist_ok=True)
out.mkdir(parents=True, exist_ok=True)
note = out / "note.txt"
note.write_text("Hello, pathlib")
print(note.exists(), note.is_file(), out.is_dir())
print(note.read_text())
for item in sorted(Path("output").iterdir()):
print(item.name, item.is_dir())
True True True
Hello, pathlib
charts True
parents=True creates both folders; exist_ok=True means no error the second time. write_text opens, writes and closes in one call. iterdir walks what's inside a folder.
from pathlib import Path
root = Path("src")
(root / "app").mkdir(parents=True, exist_ok=True)
(root / "main.py").write_text("print(1)")
(root / "notes.txt").write_text("hi")
(root / "app" / "tools.py").write_text("print(2)")
print(sorted(p.name for p in root.glob("*.py")))
print(sorted(p.name for p in root.rglob("*.py")))
print(len(list(root.rglob("*.py"))), "python files")
['main.py']
['main.py', 'tools.py']
2 python files
glob searches one folder; rglob searches every folder below it too. We sort because glob doesn't promise any order.
What with really does
f = open("data.txt", "w")
try:
f.write("one")
finally:
f.close()
print(f.closed)
with open("data.txt") as g:
print(g.closed)
print(g.closed)
True
False
True
The long way needs try and finally to close the file whatever happens. with does that for you. After the block the name still exists, but the file behind it is shut, so writing to it gives ValueError: I/O operation on closed file. Do all your work inside the block. One with can also manage two files, separated by a comma, and both close when the block ends:
from pathlib import Path
Path("in.txt").write_text("a\nb\n")
with open("in.txt") as src, open("out.txt", "w") as dst:
for line in src:
dst.write(line.upper())
print(Path("out.txt").read_text())
A
B
__enter__ and __exit__: check in, check out
Think about a hotel stay. You check in and get a key. You stay and do what you came for. At the end you check out, and if the trip goes badly, you still check out. with asks the object for two methods: __enter__ is the check-in and __exit__ is the check-out. Any object with both is a context manager.
class Tag:
def __init__(self, name):
self.name = name
def __enter__(self):
print("enter", self.name)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit", self.name, exc_type)
return False
with Tag("a") as t:
print("inside", t.name)
print("after")
enter a
inside a
exit a None
after
Whatever __enter__ returns becomes t. __exit__ always gets three values about an error: the type, the value and the traceback. There was no error, so the type is None.
When the block fails
class Tag:
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit", exc_type.__name__, exc_val)
return False
with Tag():
print("working")
1 / 0
print("never printed")
enter
working
exit ZeroDivisionError division by zero
Traceback (most recent call last):
File "S04L03_FileIO\context_error.py", line 13, in <module>
1 / 0
~~^~~
ZeroDivisionError: division by zero
Python still calls __exit__, and it receives the error. Returning False means "I didn't handle this", so the error carries on, and the traceback comes after exit has run. If __exit__ returns True instead, Python treats the error as dealt with: a class called Quiet that does this prints "caught ZeroDivisionError" and then "program keeps going", with no traceback. Use that with care; it hides the error, so only do it for errors you expect.
The shortcut: @contextmanager
from contextlib import contextmanager
@contextmanager
def tag(name):
print("enter", name)
try:
yield name
finally:
print("exit", name)
with tag("a") as t:
print("inside", t)
try:
with tag("b"):
1 / 0
except ZeroDivisionError:
print("error seen outside")
enter a
inside a
exit a
enter b
exit b
error seen outside
yield pauses the function and hands a value to the block. Everything before it is the enter part, and everything after it is the exit part. When the block fails, the error appears at the yield, so finally still prints "exit b" and the error keeps going. Without that try/finally, "exit b" would be skipped, so always keep them.
Ready-made tools in contextlib
import contextlib
import io
from pathlib import Path
print(contextlib.__name__)
with contextlib.suppress(FileNotFoundError):
Path("temp.txt").unlink()
print("no crash")
buffer = io.StringIO()
with contextlib.redirect_stdout(buffer):
print("goes to buffer")
print("captured:", buffer.getvalue().strip())
contextlib
no crash
captured: goes to buffer
suppress ignores one kind of error, like our Quiet class. redirect_stdout sends print into a StringIO, a text buffer in memory that behaves like a file, until the block ends.
Quick recap
| Tool | Use it for |
|---|---|
x, r+, b | new files only, read and write, raw bytes |
for line in f, f.read(n) | big files without loading everything |
tell, seek | see and move the file position |
Path, /, glob, rglob | join, inspect and search paths |
__enter__ / __exit__ | what with calls around your block |
@contextmanager | a context manager from one function with yield |
Try it yourself
Write a context manager that prints how long its block took. Or prompt an AI tool to write it, then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Set Up a Python AI Project with uv, VS Code and an API Key in .env
One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.
uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.
Python try and except Basics: Catch an Error and Keep Going
An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.
Read and Write a File in Python: open, with, Modes and Encoding
Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.
