Avoiding close() using with Statement for Opening Files in Python

In Python, the with statement ensures that resources like file handles, database connections, and network sockets are properly closed after use, eliminating the need to explicitly call close(). This helps prevent resource leaks and makes code more readable.

  1. The with statement is used to manage resources automatically.
  2. When the block inside with completes, Python automatically calls close() on the resource.
  3. This prevents memory leaks and file corruption in case of exceptions.
  4. The with statement works with objects that support the context manager protocol (__enter__ and __exit__ methods).

Examples

1. Reading a File Without Using close()

In this example, we use the with statement to read a file example.txt to ensure it gets closed automatically after reading.

main.py

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

# Printing file content
print(content)

Explanation:

  1. open("example.txt", "r"): Opens the file in read mode. Reference: open() builtin function
  2. file.read(): Reads the file content and stores it in content.
  3. After the with block, the file is automatically closed.

Output:

Hello User!
Hello Arjun!

2. Writing to a File Without Explicitly Closing It

The with statement also ensures safe writing to a file.

main.py

</>
Copy
# Using 'with' to write to a file
with open("output.txt", "w") as file:
    file.write("Python file handling example")

print("Data written successfully.")

Explanation:

  1. open("output.txt", "w"): Opens the file in write mode.
  2. file.write(): Writes text to the file.
  3. The file is automatically closed after exiting the with block.

Output:

Data written successfully.

Content of output.txt:

3. Handling Exceptions While Reading a File

The with statement ensures that the file is closed even if an error occurs.

main.py

</>
Copy
try:
    with open("non_existent.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("File not found.")

Explanation:

  1. open("non_existent.txt", "r"): Tries to open a non-existent file.
  2. If the file is missing, FileNotFoundError is raised.
  3. The file is still closed properly due to the with statement.

Output (if the file does not exist):

File not found.

Conclusion

In this tutorial, we have seen how the with statement is used in Python:

  1. Eliminates the need for explicitly calling close().
  2. Ensures that resources are properly closed, even in case of exceptions.
  3. Makes the code cleaner and more readable.
  4. Works with files, database connections, and other context managers.

Using with is the recommended approach for managing external resources in Python.