Context Manager

A context manager is a tool in Python that helps manage resources by ensuring proper setup and cleanup actions. It is commonly used with the with statement to handle operations like opening and closing files, acquiring and releasing locks, or managing database connections.

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# File is automatically closed when the block exits

Context manager with SQL.

import sqlite3

with sqlite3.connect("example.db") as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users")
    rows = cursor.fetchall()
    print(rows)
# Connection is automatically closed here

Have a look at reading and writing into files here - Read and write any file

Updated on