Introduction
Context managers help you manage resources like files or network connections safely and easily. They make sure resources are properly opened and closed, even if errors happen.
Jump into concepts and practice - no test required
Context managers help you manage resources like files or network connections safely and easily. They make sure resources are properly opened and closed, even if errors happen.
with open('filename.txt', 'r') as file: data = file.read()
with keyword starts a context manager block.with open('example.txt', 'w') as f: f.write('Hello!')
with open('data.txt') as file: content = file.read()
This program writes two lines to a file and then reads and prints them. The file is safely closed after each operation.
with open('test.txt', 'w') as f: f.write('Line 1\nLine 2') with open('test.txt', 'r') as f: content = f.read() print(content)
Without context managers, you must remember to close resources manually, which can cause bugs if forgotten.
Context managers handle errors gracefully by closing resources even if something goes wrong inside the block.
Context managers help manage resources safely and cleanly.
They automatically handle opening and closing resources.
Using them reduces bugs and makes code easier to read.
with open('file.txt') as f:try:
with open('test.txt', 'w') as f:
f.write('Hello')
raise Exception('Error')
except Exception:
print('Caught error')
print(f.closed)f = open('data.txt', 'r')
print(f.read())
# forgot to close the filewith open('data.txt', 'r') as f: to auto-close -> Option Awith open('data.txt', 'r') as f: to auto-close [OK]