
Python
Learn the `with` statement that automatically closes files, even if errors occur.
Forgetting to close files wastes resources.
# Manual approach - easy to forget close()
file = open("data.txt", "r")
content = file.read()
file.close() # What if an error happens before this line?
# If error occurs, file never closes!
file = open("data.txt", "r")
content = file.read()
raise Exception("Oops!") # File stays open!
file.close() # Never reached`with` automatically closes files when done, even if errors occur.
# File automatically closes when exiting 'with' block
with open("data.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed here
# No need to call file.close()# Process file safely - always closes
with open("users.txt", "r") as file:
for line in file:
user = line.strip()
print(f"Processing: {user}")
# File closed automatically
# Writing with safety
with open("output.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
# Data is saved and file closed when exiting
# Multiple files at once
with open("input.txt", "r") as in_file, open("output.txt", "w") as out_file:
content = in_file.read()
out_file.write(content.upper())| Aspect | Manual | With Statement |
|---|---|---|
| Close guarantee | No | Yes (always) |
| Error safe | No | Yes |
| Readability | Lower | Higher |
| Boilerplate | More | Less |
| Best practice | ❌ | ✅ |
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward