Sobes.tech
Junior — Middle

Can you provide an example of using a context manager to open a file in Python?

sobes.tech AI

Answer from AI

The context manager in Python is used for automatic resource management, such as opening and closing a file. This ensures that the file is properly closed even if an error occurs during execution.

Example of usage:

with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

In this example, the file is opened in read mode, and after exiting the with block, the file is automatically closed.

Can you provide an example of using a context manager… - sobes.tech