Use a with statement when code works with a resource that must be released afterward. Its head creates or connects to the resource; its indented body uses it. When the body ends, the context manager performs cleanup automatically. section 11.1.1
Read a file safely
with open("tasks.txt") as file: data = file.read() print(data) # After the block, file.closed is True The with statement removes the need for an explicit file.close() call while preserving ordinary file-reading operations. section 11.1.1
Apply the same pattern when choosing file modes or managing other shared resources:
- Use "r" for reading, "w" for writing or creating a file, and "a" for appending data. section 11.6 section 11.1.3
- Use a context manager for resources beyond files, including database connections. section 11.1.4
- Use a with-managed form to place Streamlit widgets inside that form without calling the form object for each widget. section 14.4.7
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 the complete file-reading pattern, including the with head, indented body, and representative output. section 11.1.1





