Skip to content

Python with statement | Example code

  • by

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.


with expression [as variable]:

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 the ‘open()’ method then reading the file data using the ‘read()’ method after that print the data of the 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 !')


Python with statement example

Reading file

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


Hello world, python programming.

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *