Can you explain the concept of context managers in Python and provide an example of how they can be used?
Context managers in Python are objects that define the methods __enter__() and __exit__(). They are used to manage resources, such as files or network connections, and ensure they are properly acquired and released. Context managers are typically used with the with statement. Here's an example using a file object as a context manager
# Using a context manager to work with a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# File is automatically closed outside the 'with' block
In this example, the open() function returns a file object that acts as a context manager. When the with block is entered, the file is opened, and when the block is exited, the file is automatically closed, ensuring proper resource management.