Home » Python

with keyword with example in Python

Python with keyword: Here, we are going to learn about the with keyword with example.
Submitted by IncludeHelp, on April 16, 2019

Python with keyword

with is a keyword (case-sensitive) in python, it is similar to the "using" statement in VB.net or/and C#.net. It creates a with-block that executes that usages the variable which is declared with with keyword.

with keyword is basically used to ensure that the __exit__ method is called at the end of the block. It's like a try...finally block.

It implements and follows the context manager's approach, where __enter__ and __exit__ methods are called.

For example, if you are working with the files, you may create a variable/object with with keyword for opening a file, with block may contain the file operations. And after the executing of the block, the file will be closed, no matter block has an error or not.

Syntax of with keyword

    with expression [as variable]:
	    with-block-statement(s)

Example:

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

Python examples of with keyword

Example 1: Open a file and write the text using with keyword.

# python code to demonstrate example of 
# with keyword

# Open a file and write the text using 
# "with statement"

# file name
file_name = "file1.txt"

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

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

Output

file is closed

Cotent of the file:

Welcome @ includehelp!


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.