-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwith.py
More file actions
executable file
·36 lines (23 loc) · 940 Bytes
/
with.py
File metadata and controls
executable file
·36 lines (23 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env python3
"""
with ist ein Kontextmanager.
Eine genauere Beschreibung als hier findet sich unter https://docs.python.org/3.6/reference/compound_stmts.html#with und https://docs.python.org/3.6/reference/datamodel.html#context-managers .
Hier folgen nun einige Beispiele.
"""
# Dateien öffnen
with open("../Level_04/loremipsum.txt", "r") as lorem:
print(lorem.read())
# Exceptions ignorieren
from contextlib import suppress
with suppress(ZeroDivisionError):
print(1/0)
# temporäre Dateien und Ordner
import tempfile
from os.path import join
with tempfile.TemporaryFile(mode="w") as tmpfile:
tmpfile.write("Dies ist ein Test.\n")
with tempfile.TemporaryDirectory() as tmpdir:
with open(join(tmpdir, "test.txt"), "w") as test:
test.write("Dies ist auch ein Test.\n")
# contextlib bietet Dekoratoren an um eigene Contextmanager zu erstellen:
# https://docs.python.org/3/library/contextlib.html