Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Modules, Files and Errors

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Modules, Files and Errors

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.

with Tag() as t: Python calls __enter__, whose return value becomes t; the block runs; then __exit__ is always called, with None on success or the error's type, value and traceback on failure __enter__() return value → t the block may raise __exit__(type, val, tb) always runs No error: type is None. Error: __exit__ gets it first. Return False: the error carries on. Return True: it stops there.
The promise of with: the cleanup runs even when the block fails.
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

ToolUse it for
x, r+, bnew files only, read and write, raw bytes
for line in f, f.read(n)big files without loading everything
tell, seeksee and move the file position
Path, /, glob, rglobjoin, inspect and search paths
__enter__ / __exit__what with calls around your block
@contextmanagera 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 31 of 48

Previous
Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
Next post
Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle

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.

On this page

  • More file modes
  • x: create, but never overwrite
  • r+: read and write one file
  • b: bytes, not text
  • Reading strategies
  • Every open file keeps a position
  • Paths with pathlib
  • What with really does
  • __enter__ and __exit__: check in, check out
  • When the block fails
  • The shortcut: @contextmanager
  • Ready-made tools in contextlib
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.