-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext_manger.py
More file actions
51 lines (34 loc) · 985 Bytes
/
Copy pathcontext_manger.py
File metadata and controls
51 lines (34 loc) · 985 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'''
Class based Context manager
'''
class FileManager():
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file.close()
# loading a file
with FileManager('demo.txt', '+w') as f:
f.write('Hello this done by class based')
print(f.closed)
'''
Function Based Context Manager Using contextlib Library
'''
from contextlib import contextmanager
@contextmanager
def open_file(f):
resource = open(f, '+w')
print('file_open')
try:
print("file processed")
yield resource
finally:
print("file closed")
resource.close()
with open_file('demo.txt') as resource:
resource.write("Helloo, this is done by function based context managers")
print("file updated")