Why is it considered good practice to open a file from within a python script by using with keyword

Using Open a file from within a python script by using with keyword has an advantage because it is guaranteed to close the file no matter how the nested block exits.

If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler.

You can write “with statement” in Python is used in exception handling to make the code cleaner and much more readable

Example 1: File handling without using with a statement

file = open('file_path', 'w')
file.write('hello world !')
file.close()

# another example
file = open('file_path', 'w')
try:
    file.write('hello world')
finally:
    file.close()

Example 2:

file_name = "file.txt"

# opening a file and creating with-block
with open(file_name, "w") as myfile:
    myfile.write("Welcome Developer")

# ensure that file is closed or not
if myfile.closed:
    print("File is closed")

Output:

open a file from within a python with statement

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.