Untitled Document
Context Managers - Efficiently Managing Resources
1. Introduction Click Here
#********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ ***** 
# Introduction

# Context Managers help us to effeciently use setup and teardown method 
# like working with files - if we use context managers we don't have to open and close explicitly 

       
2. Program - Class as a Context Managers Click Here
#********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****      
# Program - Class as a Context Managers 

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)

       
3. Program - Context Managers as a Function Click Here
#********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****      
# Program - Context Managers as a Function 

from contextlib import contextmanager

@contextmanager
def open_file(file, mode):
	f = open(file,mode)
	yield f 
	f.close()

with open_file('sample1.txt', 'w') as f:
	f.write('Sample File created using function as a context manager')

print(f.closed)

       
4. Program - Context Managers as a Function using try catch block Click Here
#********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****      
# Program - Context Managers as a Function using try catch block 

from contextlib import contextmanager

@contextmanager
def open_file(file, mode):
	try:
		f = open(file,mode)
		yield f 
	finally:
		f.close()

with open_file('sample1.txt', 'w') as f:
	f.write('Sample File created using function as a context manager')

print(f.closed)
       
5. Program - Practical Example OF context Managers Click Here
#********* Source Code From Website - Mangadaku - visit us at -http://mangadaku.com/ *****      
# Program - Practical Example OF context Managers
# Just run the program ans try to understand the output 

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('test1'):
	print(os.listdir())

with change_dir('test2'):
	print(os.listdir())

       
Untitled Document