File Handling with try...finally in Python
When working with files, we must always close the file to:
- Free system resources
- Avoid memory leaks
- Prevent file corruption
- Ensure data is written to disk
The finally block always executes, even if an error occurs.
Basic File Handling Without try...finally (Problem)
Python
file = open("data.txt", "r")
data = file.read()
print(data)
file.close() Problem: If an error happens before file.close(), the file remains open.
File Handling with try...finally (Correct Way)
Python
try:
# Open file in read mode
file = open("data.txt", "r")
# Read file content
data = file.read()
print(data)
finally:
# This block ALWAYS runs (even if error occurs)
file.close()
print("File closed successfully") Key Points
- try → Code that may cause an error.
- finally → Cleanup code that always executes.
Best Practice: Using with (Recommended Over try...finally)
Python provides a context manager that automatically closes files.
Python
with open("data.txt", "r") as file:
data = file.read()
print(data)
# No need to close file manually Why with is Better
- Cleaner and more readable syntax.
- No risk of forgetting to close the file.
- Automatically handles exceptions and cleanup.