Writing Functions in Python
Shayne Miel
Software Architect @ Duo Security
A context manager:
Context managers:
Caterers:
with open('my_file.txt') as my_file:
text = my_file.read()
length = len(text)
print('The file is {} characters long'.format(length))
open()
does three things:
with
with <context-manager>()
with <context-manager>(<args>)
with <context-manager>(<args>):
with <context-manager>(<args>):
# Run your code here
# This code is running "inside the context"
with <context-manager>(<args>):
# Run your code here
# This code is running "inside the context"
# This code runs after the context is removed
with <context-manager>(<args>) as <variable-name>:
# Run your code here
# This code is running "inside the context"
# This code runs after the context is removed
with open('my_file.txt') as my_file:
text = my_file.read()
length = len(text)
print('The file is {} characters long'.format(length))
Writing Functions in Python