capypad
0 Tage Serie
python / intermediate
Snippet

Ressourcenverwaltung mit Kontextmanagern

Die 'with'-Anweisung vereinfacht die Ausnahmebehandlung, indem sie Standard-Aufräumarbeiten kapselt, wie z.B. das automatische Schließen einer Datei nach Beendigung des Blocks.

snippet.py
python
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
Erklärung
1
with open(...) as file:
Öffnet die Ressource und stellt sicher, dass sie später bereinigt wird.
2
file.read()
Liest den gesamten Inhalt der Datei in eine Variable.