Objective

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.

Lesson

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.

withopen("hello.txt","r")asfile:print(file.read)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.

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.

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.

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.