File Handling with try...finally in Python

When working with files, we must always close the file to:

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

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