# Using the with statement to open and write a file with open('sample.txt', 'w') as file: file.write('Hello world') # Using the with statement to open and read a file with open('sample.txt', 'r') as file: content = file.read() print(content)
Hello world
from contextlib import contextmanager @contextmanager def managed_file(filename): file = open(filename, 'w') try: yield file finally: file.close() # Using the custom context manager with managed_file('sample2.txt') as file: file.write('Hello, World!')
class ManagedFile: def __init__(self, filename): self.filename = filename def __enter__(self): self.file = open(self.filename, 'w') return self.file def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() if exc_type is not None: print(f"An exception occurred: {exc_type}, {exc_val}") # Using the class-based context manager with ManagedFile('sample3.txt') as file: file.write('Hello, again!')
import sqlite3 from contextlib import contextmanager @contextmanager def open_database(db_name): connection = sqlite3.connect(db_name) cursor = connection.cursor() try: yield cursor finally: connection.commit() connection.close() # Using the database context manager with open_database('example.db') as cursor: cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)') cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))
import time from contextlib import contextmanager @contextmanager def timer(): start = time.time() try: yield finally: end = time.time() print(f"Elapsed time: {end - start} seconds") # Using the timer context manager with timer(): time.sleep(2) # Simulate a time-consuming task
Elapsed time: 2.004432201385498 seconds