VOOZH about

URL: https://thenewstack.io/how-to-use-the-with-statement-in-python/

⇱ How to Use the with Statement in Python - The New Stack


TNS
SUBSCRIBE
Join our community of software engineering leaders and aspirational developers. Always stay in-the-know by getting the most important news and exclusive content delivered fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter in the past. Click the button below to open the re-subscribe form in a new tab. When you're done, simply close that tab and continue with this form to complete your subscription.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!

We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.

What’s next?

Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.

Follow TNS on your favorite social media networks.

Become a TNS follower on LinkedIn.

Check out the latest featured and trending stories while you wait for your first TNS newsletter.

PREV
1 of 2
NEXT
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
Thanks for your opinion! Subscribe below to get the final results, published exclusively in our TNS Update newsletter:
NEW! Try Stackie AI
From clobbered drafts to real-time sync
Apr 14th 2026 10:00am, by David Moore
TypeScript 6.0 RC arrives as a bridge to a faster future
Mar 14th 2026 9:00am, by Darryl K. Taft
Mastra empowers web devs to build AI agents in TypeScript
Jan 28th 2026 11:00am, by Loraine Lawson
2024-02-02 07:44:46
How to Use the with Statement in Python
tutorial,
Python / Software Development / Software Testing

How to Use the with Statement in Python

Learn how to use the with statement in the Python programming language.
Feb 2nd, 2024 7:44am by Jack Wallen
👁 Featued image for: How to Use the with Statement in Python

Error handling is a very important concept in programming. Without error handling, your applications wouldn’t be able to effectively handle abnormal input or conditions and would, most likely, fail to run or remain running. As a Python programmer, you need to ensure your applications are capable of countering errors that may have been brought about by users or your own code. 

This can be tricky but fortunately, Python has a statement that makes it a bit easier. That statement is with and it serves to not only help your programs deal with errors but also to make your code far cleaner and easier to read (which is important within the realm of Python) and replaces the more convoluted try/finally statement.

Let me show you a simple application that uses the try/finally statement and then I’ll demonstrate the same application using with. This application will simply create a new file and write the text “Hello New Stack” to it. We’ll use the open(), write(), and close() functions to achieve this task (each of which is available in the standard library (so you don’t have to import anything first).

The try/finally version of this code looks like this:

A brief explanation:

  • file = open(‘test_file’, ‘w’) – defines the file variable by creating a new file, called test_file, with write permissions.
  • try – tells Python we’re going to test a block of code for errors.
  • file.write(‘Hello New Stack’) – instructs Python that we’re going to write Hello New Stack to the file defined by the variable.
  • finally – ends the block of code being tested for errors.
  • file.close() – closes the test_file.

Create that file using your editor of choice (naming it tryfinally.py) and run it with:

python3 tryfinally.py

You shouldn’t see any output, but if you view the contents of test_file, it should read:

Hello New Stack

Okay, let’s do the same thing, only this time we’ll use the with statement. We can now do this with only two lines that look like this:

An explanation:

  • with open(“test_file”, “w”) as file: – this does two things: opens test_file for writing and then automatically closes it after the write process.
  • file.write(“Hello New Stack”) – writes the content within quotes to test_file.

Run this program and you’ll see the same results as you did in the app that used the try/finally statement. The difference is, that we were able to more cleanly and efficiently use error-handling. Although there is nothing wrong with using try/finally, the goal with Python is to write cleaner code that is more easily readable. By using fewer lines of code, you are less likely to introduce errors.

The true beauty of with is that it takes care of actions that would otherwise require more code to deal with (such as the opening and closing of a file).

Of course, with doesn’t just work with open(). You can even create objects that support with. Let’s create an object for file writing that uses with. We’ll do the same thing we did above (write Hello World to test_file), only this time we’ll do so by creating an object that will employ with

There are a few things of note. We’re going to employ the following:

  • class – this serves as a code template for creating our object
  • def – a keyword used to define a function.
  • __init__ – initializes a newly-created object
  • __enter__ – return value is bound to the with target variable.
  • __exit__ – deals with special cases that might happen within a block of code.

Our code looks like this:

The line-by-line looks like this:

  • class TextWriter(object): – we’re naming our class (TextWriter) as an object.
  • def __init__(self, file_name): – initialize our object and makes it possible access the variable file_name
  • self.file_name = file_name defines self.file_name as file_name
  • def __enter__(self): – binds with to file_name (as defined by self)
  •  self.file = open(self.file_name, ‘w’) – ensure our file is opened with write permissions.
  • return self.file – returns the result to the original caller
  • def __exit__(self, *args): – uses *args to pass a variable number of arguments to the function.
  • self.file.close() – closes an open file.
  • with TextWriter(‘test_file’) as tfile: – uses the with statement to handle errors for our TextWriter object and defines it as tfile, opens test_file for writing, and then closes it when the write() function completes its task.
  • tfile.write(‘Hello New Stack’) – writes Hello New Stack to tfile.

When you run the program, you’ll get the same output as you did before (Hello New Stack written to test_file).

With is a very powerful and handy tool for Python error handling. By replacing the try/finally method with a more concise block of code, you not only ensure your programs reliably close resources after they are used, but you also write cleaner code that introduces fewer errors.

TRENDING STORIES
Jack Wallen is what happens when a Gen Xer mind-melds with present-day snark. Jack is a seeker of truth and a writer of words with a quantum mechanical pencil and a disjointed beat of sound and soul. Although he resides...
Read more from Jack Wallen
SHARE THIS STORY
TRENDING STORIES
SHARE THIS STORY
TRENDING STORIES
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.