Understand Python With Statement: A Beginner Guide – Python Tutorial

By | December 11, 2019

Python with statement is widely used in python script. How to use it correctly? In this tutorial, we will discuss this top for python beginners. You can learn it by following our tutorial.

Syntax

Python with statement can be:

with context [as var]:
    pass

where context is an expression, it will return an object and will be saved in var.

Here is an example:

with open("data.txt") as f:
    print(type(f))

In this example, open(“data.txt”) will return a _io.TextIOWrapper object and this object will be saved into variable f.

Why use python with statement?

The main reason is with statement will execute some extra operations when it is finished.

For example:

with open("data.txt") as f:
    print(type(f))
print(f.closed)
print("--end--")

Run this python script, you will get result:

<class '_io.TextIOWrapper'>
True
--end--

From output above we can find: with statement will close the file when it is finished. We do not need to close this file manully. Python with statement do it for us.

We also can find: the variable created by python with statement is global.

As example above, variable f will work fine in the whole python script, not only in with statement.

Leave a Reply