Created
September 2, 2019 09:30
-
-
Save asnimansari/4d2a6bafdb60824354939b5794764984 to your computer and use it in GitHub Desktop.
Custom python context manager definition & its usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Context manager definition | |
class FileOpen(object): | |
def __init__(self, file_name, method): | |
self.file_object = open(file_name, method) | |
def __enter__(self): | |
return self.file_object | |
def __exit__(self, value, type, traceback): | |
self.file_object.close() | |
# Example usage | |
with FileOpen('discot.txt', 'w') as opened_file: | |
opened_file.write("I am a disco dancer") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment