Skip to content

Python with keyword | Example code

  • by

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]:
	    with-block-statement(s)

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")

Output:

Python with keyword example

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 *