Created
June 3, 2023 16:51
-
-
Save eder-projetos-dev/437b9c7fb5153ab4a89936576f074654 to your computer and use it in GitHub Desktop.
Python - Context managers
This file contains 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
# Traditional approach | |
file = open("data.txt", "r") | |
try: | |
data = file.read() | |
# Process the data | |
finally: | |
file.close() | |
# Context manager | |
with open("data.txt", "r") as file: | |
data = file.read() | |
# Process the data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can context managers improve the efficiency of my code?
Context managers are an excellent tool for managing resources efficiently and ensuring proper cleanup. They allow you to allocate and release resources automatically by defining a setup and teardown code block. One of the most common use cases of context managers is working with files, where they handle opening and closing operations seamlessly.
https://levelup.gitconnected.com/11-tricks-that-will-make-your-life-easier-as-a-python-developer-da29e4306675