Close a File Properly in Python

To close a file properly in Python, you should use the close() method on the file object after performing read or write operations. Alternatively, the with statement ensures the file is closed automatically, even if an error occurs during file handling.


Examples

1. Closing a File Using close() Method

In this example, we open a file, perform an operation, and then close it using the close() method.

</>
Copy
# Opening a file in write mode
file = open("example.txt", "w")

# Writing data to the file
file.write("Hello, Python!")

# Closing the file
file.close()

# Checking if the file is closed
print("Is file closed?", file.closed)

Explanation:

  • open("example.txt", "w") – Opens the file in write mode.
  • file.write("Hello, Python!") – Writes a string to the file.
  • file.close() – Closes the file explicitly.
  • file.closed – Returns True if the file is properly closed.

Output:

Using close() ensures the file is released from memory after the operation.

2. Using the with Statement for Automatic File Closing

The with statement automatically closes the file when the block of code is exited.

</>
Copy
# Using with statement to open a file
with open("example.txt", "r") as file:
    content = file.read()
    print("File content:", content)

# Checking if the file is closed
print("Is file closed?", file.closed)

Explanation:

  • open("example.txt", "r") – Opens the file in read mode.
  • file.read() – Reads the file content.
  • with – Ensures that the file is closed automatically when the block ends.
  • file.closed – Returns True after the with block is exited.

Output:

The with statement is the recommended way to handle files in Python as it ensures proper closure.

3. Handling File Closing in Case of Exceptions

If an error occurs before calling close(), the file may remain open. We can handle this using try-finally to ensure the file is closed.

</>
Copy
try:
    file = open("example.txt", "r")
    content = file.read()
    print("File content:", content)
except Exception as e:
    print("An error occurred:", e)
finally:
    file.close()
    print("File closed in finally block:", file.closed)

Explanation:

  • try – Attempts to open and read the file.
  • except – Catches any errors if the file does not exist.
  • finally – Ensures that file.close() is executed.

Output:

The finally block ensures the file is closed even if an error occurs, preventing resource leaks.

4. Checking if a File is Already Closed

We can check if a file is already closed before attempting operations on it.

</>
Copy
# Opening and closing a file
file = open("example.txt", "r")
file.close()

# Checking if file is closed
if file.closed:
    print("The file is already closed.")
else:
    file.write("New data")  # This will raise an error if executed

Explanation:

  • file.closed – Returns True if the file is closed.
  • Checking before performing operations prevents unintended errors.

Output:

By checking file.closed, we avoid errors when working with closed files.

Conclusion

Properly closing files in Python prevents resource leaks. Here’s a summary of examples that we covered in this tutorial:

  1. Use close() explicitly after operations.
  2. Prefer the with statement for automatic closure.
  3. Use try-finally to handle exceptions and ensure closure.
  4. Check file.closed before performing operations on a file.