Created
August 10, 2020 09:11
-
-
Save AntiKnot/925c2229f3d99243a6e75692fc0612c0 to your computer and use it in GitHub Desktop.
实现上下文管理 with
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
| import contextlib | |
| @contextlib.contextmanager | |
| def my_open(file_name): | |
| # __enter__ | |
| print('open file: ', file_name, 'in_enter') | |
| file_handler = open(file_name) | |
| yield file_handler | |
| # __exit__ | |
| print('close file:', file_name, 'in_exit') | |
| file_handler.close() | |
| return | |
| if __name__ == '__main__': | |
| with open('hello.txt') as f: | |
| for line in f: | |
| print(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment