Python Context Managers in 10 Minutes — using the ‘with’ keyword

Context managers made simple with sample usage examples

Kay Jan Wong
Towards Data Science
5 min readFeb 21, 2022

--

Context managers are essentially generators that yield a single value. The topic may seem foreign to you now, but you would most likely have used a context manager before. The most commonly used context manager is the Python built-in open command which opens a file, and is usually used together with a with keyword as such,

with open("file.txt", "r") as file:
data = file.read()

--

--

Data Scientist, Machine Learning Engineer, Software Developer, Programmer | Someone who loves coding, and believes coding should make our lives easier