Created
March 30, 2024 22:21
-
-
Save normanlmfung/1765bd4dca5987c352f33304ad91e5f2 to your computer and use it in GitHub Desktop.
python_syntax_using_enter_exit
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
class MessageWriter(object): | |
def __init__(self, file_name): | |
self.file_name = file_name | |
def __enter__(self): | |
self.file = open(self.file_name, 'w') | |
return self.file | |
def __exit__(self, *args): | |
self.file.close() | |
with MessageWriter('my_file.txt') as xfile: | |
xfile.write('hello world') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment