Skip to content

Q&A · Answered

How to use context managers (with statement) in Python

asked 9 months, 1 week ago 1688 views 1 answer
38

I see "with" statements used in Python. What are context managers and how do I create my own?

1 Answer

One accepted
13

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Using context managers

# File handling (automatic close)
with open('file.txt', 'r') as f:
    content = f.read()

# Multiple context managers
with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
    fout.write(fin.read())

Creating custom context manager

from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.time()
    yield
    end = time.time()
    print(f"Elapsed: {end - start:.2f}s")

# Usage
with timer():
    # code to time
    time.sleep(1)

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.