Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python with Keyword



The Python with keyword replaces a try-finally block. It is a case-sensitive. It can be used in file handling and handling database. A function or class that supports the with statement is known as a context manager.

A context manager allows you to open and close resources when we want to. For example, the open() function is a context manager. When we call the open() function using the with statement, the file closes automatically after we have processed the file.

Syntax

Following is the syntax of the Python with keyword −

with

Using 'with' Keyword in Files

The with keyword is used in files to open a particular file and perform various operations.

Example

Here, we have opened the sample.txt file in read mode using with keyword −

def Tutorialspoint():
	with open('sample.txt') as Tp:
		data = Tp.read()
    # Printing our text
	print(data)
    
Tutorialspoint()

Output

Following is the output of the above code −

Hello welcome to Tutorialspoint

Using 'with' Keyword in Database

The with statement is useful for managing database connections, ensuring that the connection is closed even if an error occurs.

Example

Following is an example of usage of with in database −

import sqlite3

with sqlite3.connect('example.db') as conn:
    cursor = conn.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
    cursor.execute('INSERT INTO users (name) VALUES (?)', ('Python',))
    cursor.execute('INSERT INTO users (name) VALUES (?)', ('Java',))
    cursor.execute('INSERT INTO users (name) VALUES (?)', ('C',))
    cursor.execute('INSERT INTO users (name) VALUES (?)', ('C++',))
    conn.commit()

# Fetching data
with sqlite3.connect('example.db') as conn:
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM users')
    print(cursor.fetchall())

Output

Following is the output of the above code −

[(1, 'Python'), (2, 'Java'), (3, 'C'), (4, 'C++')]
python_keywords.htm
Advertisements