-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_managers.py
46 lines (34 loc) · 1.03 KB
/
context_managers.py
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
37
38
39
40
41
42
43
44
45
46
# Context Managers
from contextlib import contextmanager
@contextmanager
def open_managed_file(filename):
with open(filename, 'a') as file:
try:
yield file
finally:
file.close()
with open_managed_file('notes.txt') as file:
print("Managing file...")
file.write("\nUsage - contextlib module")
print("File Managed.")
class ManageFile:
def __init__(self, filename):
print('FILE MANAGER')
self.filename = filename
def __enter__(self):
print('Opening file..')
self.file = open(self.filename, 'a')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
print('File closed.')
with ManageFile('notes.txt') as filename:
print('Writing to file...')
filename.write('\nManaging File Context.')
# Trial
with open('notes.txt', 'a') as file:
try:
file.write('\nContext Managers.')
finally:
file.close()