Skip to content

Python, the `with` statement

New Course Coming Soon:

Get Really Good at Git

The with statement is very helpful to simplify working with exception handling.

For example when working with files, each time we open a file, we must remember to close it.

with makes this process transparent.

Instead of writing:

filename = '/Users/flavio/test.txt'

try:
    file = open(filename, 'r')
    content = file.read()
    print(content)
finally:
    file.close()

You can write:

filename = '/Users/flavio/test.txt'

with open(filename, 'r') as file:
    content = file.read()
    print(content)

In other words we have built-in implicit exception handling, as close() will be called automatically for us.

with is not just helpful to work with files. The above example is just meant to introduce its capabilities.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Python Handbook
→ Get my Python Handbook

Here is how can I help you: