How to use context managers (with statement) in Python
Answered
38
I see "with" statements used in Python. What are context managers and how do I create my own?
D
Asked by
db_admin
Silver
•
415 rep
1 Answer
13
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)
D
Gold
•
290 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer