Find Mistake: File Not Closed
Find the Mistake Medium
Question
This code works but has a resource leak. What is wrong?
Code
f = open("data.txt", "r")
content = f.read()
print(content)
Hint
Files should always be closed after use.
Explanation
The file is never closed, which can cause resource leaks and locked files. The fix is to use a context manager: with open('data.txt', 'r') as f: content = f.read() — the with statement ensures the file is closed automatically.
Related Resources
Related Lessons
- File Handling
Context managers.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.