×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python with Keyword

By IncludeHelp Last updated : December 07, 2024

Description and Usage

The 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.

The 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

Syntax of with keyword:

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

Sample Input/Output

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

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!

Example 2

# Using 'with' to open a file
with open("example.txt", "r") as file:
    # Reading the file content
    content = file.read()
    print(content)

Comments and Discussions!

Load comments ↻





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