Python - Context Managers : Efficiently Managing Resources
** Context Managers - Efficiently Managing Resources
==========================================
class Open_File():
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, traceback):
self.file.close()
with Open_File('sample.txt', 'w') as f:
f.write('Testing')
print(f.closed)
---------------------------------
True
---------------------------------
Testing <~~ sample.txt
---------------------------------
==========================================
from contextlib import contextmanager
@contextmanager
def open_file(file, mode):
f = open(file, mode)
yield f
f.close()
with open_file('sample.txt', 'w') as f:
f.write('Hi, LinuxerHAN !!')
print(f.closed)
---------------------------------
True
---------------------------------
Hi, LinuxerHAN !! <~~ sample.txt
---------------------------------
==========================================
import os
from contextlib import contextmanager
cwd = os.getcwd()
os.chdir('Sample-Dir-One')
print(os.listdir())
os.chdir(cwd)
cwd = os.getcwd()
os.chdir('Sample-Dir-Two')
print(os.listdir())
os.chdir(cwd)
---------------------------------
['1-1.txt', '1-2.txt', '1-3.txt']
['2-1.txt', '2-2.txt', '2-3.txt']
---------------------------------
==========================================
import os
from contextlib import contextmanager
@contextmanager
def change_dir(destination):
try:
cwd = os.getcwd()
os.chdir(destination)
yield
finally:
os.chdir(cwd)
with change_dir('Sample-Dir-One'):
print(os.listdir())
with change_dir('Sample-Dir-Two'):
print(os.listdir())
---------------------------------
['1-1.txt', '1-2.txt', '1-3.txt']
['2-1.txt', '2-2.txt', '2-3.txt']
---------------------------------