python / intermediate
Snippet
Managing Resources with Context Managers
The 'with' statement simplifies exception handling by encapsulating standard clean-up tasks, like closing a file automatically after the block finishes.
snippet.py
1
2
3
4
5
6
try:with open('data.txt', 'r') as file:content = file.read()except FileNotFoundError:print('File not found')# File is automatically closed here even if an error occurs
Breakdown
1
with open(...) as file:
Opens the resource and ensures it is cleaned up later.
2
file.read()
Reads the entire content of the file into a variable.