A context manager controls entry into and exit from a resource-handling context. In Python, the with statement connects a resource, lets the body use it, and releases it when execution leaves the block. section 11.1.1
Read a file safely
with open("tasks.txt") as file: data = file.read() print(data) assert file.closed The file is closed automatically after the indented body finishes, avoiding a separate close call. section 11.1.1 section 11.6
Listing 11.2 Using with to open a file
with open("tasks.txt") as file: #1
print(f"file object: {file}")
data = file.read()
print(data)
# output the following lines:
file object: <_io.TextIOWrapper name='tasks.txt' mode='r' encoding='UTF-8'>
1001,Homework,5
1002,Laundry,3
1003,Grocery,4
Inspect a complete with statement that opens tasks.txt, reads its contents, and demonstrates the resulting output. section 11.1.1
Apply context management when:
- Reading or writing files, because the context manager closes the shared file resource automatically. section 11.6
- Working with shared resources such as database connections. section 11.1.4
- Grouping Streamlit form operations, allowing widgets created inside the block to belong to that form. section 14.4.7



