Python with statement | Example code

Python with statement is used with try/finally statements. It is used with unmanaged resources (like file streams). The with the statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed.

Syntax

with expression [as variable]:
    with-block

Example “with statement” in Python

Simple example code using “with statement”.

In the normal file operation, we have to follow some rules, like opening the file using ‘open()’ method then read the file data using ‘read()’ method after that print the data of file and when all operation gets over we need to close the file using ‘close()’ method.

Using the “With-statement”, we can get automatic exception handling and better syntax.

Example: Writing file

with open('file_path', 'w') as file:
    file.write('Hello world !')

Output:

Python with statement example

Reading file

with open('file.txt') as infile:
    for line in infile:
        print(line)

Output:

Hello world, python programming.

Do comment if you have any doubts and suggestions on this Python keyword tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe 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.