with open()
to Handle Files in Python
In Python, the with open()
statement is used to ensures that the file is properly closed after its suite finishes executing, even if an error occurs. This method prevents resource leaks and improves code readability.
Explanation:
- The
open()
function is used to open a file in different modes such as read ('r'
), write ('w'
), append ('a'
), or binary mode ('rb'
,'wb'
). - The
with
statement ensures that the file is closed automatically, eliminating the need for explicitclose()
calls. - The file object returned by
open()
is used to read, write, or modify the contents of the file. - Using
with open()
improves error handling by ensuring files are properly closed even if exceptions occur.
Examples
1. Reading a File Using with open()
In this example, we use with open()
to read the contents of a file example.txt safely.

main.py
# Using with open() to read a file
with open("example.txt", "r") as file:
content = file.read()
# Printing the file content
print(content)
Explanation:
- The file
"example.txt"
is opened in read mode ("r"
) usingwith open()
. - The
read()
method is used to read the entire file content and store it in the variablecontent
. - The file is automatically closed once the
with
block ends, ensuring safe handling.
Output:
Hello User!
Hello Arjun!
2. Writing to a File Using with open()
We use with open()
to write data to a file safely.
main.py
# Using with open() to write to a file
with open("output.txt", "w") as file:
file.write("Hello, World!")
# File is automatically closed after exiting the block
Explanation:
- The file
"output.txt"
is opened in write mode ("w"
), which creates the file if it does not exist or overwrites it if it does. - The
write()
method is used to add the string"Hello, World!"
to the file. - The file is automatically closed when the
with
block ends.
Output (File Content of output.txt):

3. Appending Data to a File Using with open()
Appending allows us to add new content to an existing file without overwriting its previous data.
main.py
# Using with open() to append to a file
with open("output.txt", "a") as file:
file.write("\nAppending new content!")
# File is automatically closed after exiting the block
Explanation:
- The file
"output.txt"
is opened in append mode ("a"
), allowing us to add new data without erasing the existing content. - The
write()
method is used to append a new line"\nAppending new content!"
to the file. - The file is automatically closed after execution, ensuring proper resource management.
Output (Updated Content of output.txt):

4. Reading a File Line by Line Using with open()
Instead of reading an entire file at once, we can read it line by line using a loop.

main.py
# Using with open() to read a file line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Explanation:
- The file
"example.txt"
is opened in read mode ("r"
). - The
for
loop iterates over each line in the file. - The
strip()
method is used to remove any leading or trailing whitespace from each line before printing.
Output:
Hello User!
Hello Arjun!
Conclusion
Using with open()
is the safest way to handle files in Python because:
- It ensures that files are automatically closed after execution.
- It prevents resource leaks and reduces the chances of file corruption.
- It improves readability and error handling in Python file operations.
By following these examples, you can efficiently read, write, and append data to files while ensuring safe resource management.