How to Close a File in Python?

In this tutorial, I will explain how to close a file in Python after opening it. Recently in a Python webinar on the topic of files, someone raised a question about closing a file. After discussion, we found several effective methods to achieve this task. I will explain those important methods with examples.

Close a File in Python

Let us learn how to close a file in Python.

Read How to Save Variables to a File in Python?

1. Use the close() Method

Let’s consider a real-world scenario where we need to process a file containing customer information for a company based in New York. Here’s an example of how to open a file, perform some operations, and then close it using the close() method in Python:

# Open the file
customer_file = open("customers.txt", "r")
contents = customer_file.read()

num_customers = len(contents.split("\n"))
print(f"Total customers in New York: {num_customers}")

# Close the file
customer_file.close()

Output :

Total customers in New York: 4

I executed the above example code and added the screenshot below.

Close a File in Python

In this example, we open the “customers.txt” file in read mode using open(). We then read the contents of the file using the read() method and process the data to count the number of customers. Finally, we close the file using the close() method to release the resources.

It’s important to note that you should be able to explicitly close the file by calling file.close(). Also, Python does not close a file right when it is done with it, similar to how it handles memory.

Check out How to Write a Variable to a File in Python?

2. Use the with Statement

Python provides a more convenient way to handle Python file operations and automatically close files using the with statement. The with statement ensures that the file is properly closed after the block of code inside it is executed, even if an exception is raised.

Here’s an example of using the with statement to process a file containing employee information for a company in California:

with open("employees.txt", "r") as employee_file:
    # Read the contents of the file
    contents = employee_file.read()

    # Process the contents
    num_employees = len(contents.split("\n"))
    print(f"Number of employees in California: {num_employees}")

Output:

Number of employees in California: 4

I executed the above example code and added the screenshot below.

How to Close a File in Python

In this example, we use the with statement to open the “employees.txt” file in read mode. The file is automatically closed when the block of code inside the with statement is finished, even if an exception occurs.

To close files properly, the most simple solution that follows best practices is to use what’s called a with statement whenever opening a file.

Read Python Create File

Handle Exceptions

When working with Python files, it’s a good practice to handle exceptions that may occur during file operations. This ensures that the file is properly closed even if an error occurs. Here’s an example:

try:
    # Open the file
    sales_file = open("sales_data.txt", "r")

    # Process the file contents
    total_sales = calculate_total_sales(sales_file)
    print(f"Total sales in the USA: ${total_sales}")

except FileNotFoundError:
    print("File not found.")

finally:
    # Close the file
    sales_file.close()

In this example, we use a try-except-finally block to handle potential exceptions. The try block contains the code that may raise an exception. If a FileNotFoundError occurs, we catch it in the except block and print an error message. The finally block ensures that the file is closed regardless of whether an exception occurred or not.

Always use the close() method in conjunction with a try-finally block to guarantee proper closure, whether you are reading from or writing to a file.

Check out Python Get Filename From Path

Conclusion

In this tutorial, I explained how to close a file in Python, use the close() method explicitly, and handle exceptions while closing files. We also explored the with statement, which provides a more convenient and secure way to manage file operations.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.