Python/With Statement


Books-aj.svg aj ashton 01f.png
  • Learn about the with statement, its purpose, and its relationship with the try statement.
  • Learn how and when to use the with statement.
  • Learn how to create objects that can be used with the with statement.


Note: This lesson is diving pretty deep into the world of Python and it's recommended that you've finished both Definitions and Object-Oriented Programming on this course. If you haven't, you can skip to the next lesson.

The With Statement

The with statement is an error handling statement, similar to the try statement. The with statement is used to cleanup objects automatically. This helps reduce the amount of code that needs to be written, since the finally statement and the object's manually written cleanup is omitted.

To use the with statement, you'll need to specify an object you want to use followed by the as statement, which then ends with the variable name of that object. Here is an example using the with statement, assuming that the file hello.txt has the sentence Hello, world! in it.

with open("hello.txt", "r") as file:
Hello, world!

An example using the try, except, and finally statements. Again, it assumes that the file hello.txt has the sentence Hello, world! in it.

    file = open("hello.txt", "r")
except IOError:
    print("An I/O error has occurred!")
    print("An unknown error has occurred!")
Hello, world!

However, if an error occurs while the file is open, the file will not be closed. Previously, one would have to write a try...finally block to ensure a proper cleanup of objects, which would require a lot more work and sacrifice readability.

Further information

  1. PEP 343: The 'with' statement, Python documentation


Crystal Clear app kedit.svg

Tulliana launch.png Completion status: this resource is just getting off the ground. Please feel welcome to help!

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.


Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us  |  About |  IT Training & References |  IT Careers |  IT Hardware |  IT Software |  IT Books