with

In Python, the with keyword wraps the execution of a block of code within methods defined by a context manager. This keyword is especially helpful for ensuring that resources are properly acquired and released. It automatically handles setup and teardown actions, such as opening and closing files or acquiring and releasing locks, making your code more robust and less error-prone.

Python with Keyword Examples

Here’s a quick example to illustrate how you can use the with keyword with file handling:

Python
>>> with open("example.txt", mode="w", encoding="utf-8") as file:
...     file.write("Hello, Pythonista!")
...
17

>>> with open("example.txt", mode="r", encoding="utf-8") as file:
...     content = file.read()
...

>>> content
'Hello, Pythonista!'

In this example, the with statement is used to open a file named example.txt for writing and then for reading. The statement ensures that the file is properly closed after the block of code is executed, even if an error occurs.

Python with Keyword Use Cases

  • Automatically managing file opening and closing
  • Ensuring proper acquisition and release of resources like locks, sockets, and database connections
  • Simplifying the code for handling exceptions and cleanup actions

Tutorial

Context Managers and Python's with Statement

In this step-by-step tutorial, you'll learn what the Python with statement is and how to use it with existing context managers. You'll also learn how to create your own context managers.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader