Skip to content

Instantly share code, notes, and snippets.

@rongpenl
Created May 29, 2023 04:23
Show Gist options
  • Save rongpenl/2ec6d35299c709517f3ac6a5c7a7a679 to your computer and use it in GitHub Desktop.
Save rongpenl/2ec6d35299c709517f3ac6a5c7a7a679 to your computer and use it in GitHub Desktop.
Cracking Intermediate Python Episode 1: Context Manager
from contextlib import contextmanager
@contextmanager
def open_file(path, mode):
try:
file = open(path, mode)
yield file
finally:
file.close()
with open_file('file.txt', 'w') as f:
f.write('Hello, world!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment