A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_with_keyword.htm below:

Python with Keyword

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4