Opening and Closing Files in Python: A Beginner’s Guide | Python tutorials on BeingSkilled

Working with files is an essential part of programming, and Python makes it easy to open, read, write, and close files with built-in functions. Understanding how to properly open and close files is the foundation of effective file handling in Python.

In this post, we’ll explore different ways to open and close files using Python, including best practices and real-world examples.

1. Using open() to Open a File

The open() function is used to open a file. It returns a file object which can then be used for reading, writing, or appending data.

Syntax:

file = open("filename", "mode")

Modes:

  • 'r' – Read (default)
  • 'w' – Write (creates or truncates file)
  • 'a' – Append
  • 'x' – Create
  • 'b' – Binary mode
  • 't' – Text mode (default)

Example 1: Opening a File in Read Mode

file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()

2. Closing a File with close()

Once you're done with file operations, it's important to close the file using file.close(). This frees up system resources and ensures that changes are saved correctly.

Example 2: Closing a File After Writing

file = open("notes.txt", "w")
file.write("This is a new file.")
file.close()

Not closing a file can lead to data corruption or memory leaks in long-running applications.

3. Best Practice: Using with Statement

The with statement is the recommended way to work with files in Python. It automatically takes care of closing the file, even if errors occur during file operations.

Example 3: Reading a File with with

with open("data.txt", "r") as file:
    content = file.read()
    print(content)

Example 4: Writing with with

with open("log.txt", "w") as file:
    file.write("Log entry added.")

4. Checking If a File Is Closed

You can check the file’s status using the file.closed attribute.

Example 5: Checking Closed Status

file = open("info.txt", "r")
print(file.closed)  # Output: False
file.close()
print(file.closed)  # Output: True

5. Opening Non-Existent Files

Attempting to open a non-existent file in read mode results in an error. Use exception handling to manage such cases.

Example 6: Handling File Not Found

try:
    file = open("missing.txt", "r")
    print(file.read())
    file.close()
except FileNotFoundError:
    print("File does not exist.")

6. Summary Table

Method Purpose Example
open() Open a file in specified mode open("file.txt", "r")
close() Close a file file.close()
with Automatically manage file open/close with open(...) as f:
file.closed Check if file is closed file.closed

7. Final Thoughts

Opening and closing files properly is crucial when working with file I/O in Python. While open() and close() give you manual control, the with statement is the safest and cleanest method to ensure files are closed automatically. Use it whenever possible to write more robust and readable Python code.