Python with keyword | Example code

In python the with keyword is used when working with unmanaged resources (like file streams). . It provides ‘syntactic sugar’ for try/finally blocks.

Syntax of with keyword

  with expression [as variable]:

Python Example of “with keyword”

Simple example code. It creates a with-block that executes that usages the variable which is declared with “with keyword“.

The with keyword is basically used to ensure that the __exit__ method is called at the end of the block.

Example: Open a file and write the text.

file_name = "file.txt"

# opening a file and creating with-block
with open(file_name, "w") as myfile:
    myfile.write("Welcome Developer")

# ensure that file is closed or not
if myfile.closed:
    print("File is closed")


Python with keyword example

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.