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.
- The
with
statement is used to manage resources automatically. - When the block inside
with
completes, Python automatically callsclose()
on the resource. - This prevents memory leaks and file corruption in case of exceptions.
- 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:
open("example.txt", "r")
: Opens the file in read mode. Reference: open() builtin functionfile.read()
: Reads the file content and stores it incontent
.- 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:
open("output.txt", "w")
: Opens the file in write mode.file.write()
: Writes text to the file.- 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:
open("non_existent.txt", "r")
: Tries to open a non-existent file.- If the file is missing,
FileNotFoundError
is raised. - 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:
- Eliminates the need for explicitly calling
close()
. - Ensures that resources are properly closed, even in case of exceptions.
- Makes the code cleaner and more readable.
- Works with files, database connections, and other context managers.
Using with
is the recommended approach for managing external resources in Python.