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()
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")
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.