Python With Statement | Keyword | Examples

Python With statement will auto close the nested block of code. It has guaranteed to close the file (if using in file handling) or nested loop, this is the main advantage of it. And also get better syntax and exception handling.

The With Statement added in python Python 2.5, as an optional feature. Then after Python version 2.6 makes a with as a keyword, means no need special enabled.

Python With Statement Keyword Examples

Syntax

Here is basic control-flow and syntax:

with expression [as variable]:
    with-block

Python With statement Example

Here is an example of open a file and reading the text line by line.

When the statement has finished, the file object in f will clean up automatically and closed. even The condition where if the for loop raised an exception part-way through the block.

with open('testFile.txt', 'r') as f:
    for line in f:
        print(line)

Output: EyeHunts

Python

Tutorial

Another Example

Let’s see the same example with python try except block (python exception handling). As you can see we have to use the finally block to close a file “f” object. here you have to ensure finally block proper cleanup of objects

try:
    f = open("testFile.txt", "r")
    print(f.read())
except IOError:
    print("An I/O error has occurred!")
except:
    print("An unknown error has occurred!")
finally:
    f.close()

QA: When using a Python With statement? [Interview Question]

Whenever you are handling unmanaged resources (like file streams) then you can use Python With keyword (statement).

It allows you to ensure that a resource is “cleaned up” when the code that uses it finishes running, even if exceptions are thrown. It provides ‘syntactic sugar‘ for try/finally blocks.

Reference: https://docs.python.org/3/whatsnew/2.6.html#pep-343-the-with-statement (Official document)

So overall you can improve your syntax and application stability using a “With Keyword”. Do comment if you have any suggestions, doubts, or any new example with an explanation.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples with statements are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.