{"id":5290,"date":"2021-05-10T09:31:54","date_gmt":"2021-05-10T04:01:54","guid":{"rendered":"https:\/\/python-programs.com\/?p=5290"},"modified":"2021-11-22T18:42:49","modified_gmt":"2021-11-22T13:12:49","slug":"python-open-a-file-using-open-with-statement-and-benefits-explained-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-open-a-file-using-open-with-statement-and-benefits-explained-with-examples\/","title":{"rendered":"Python: Open a file using \u201copen with\u201d statement and benefits explained with examples"},"content":{"rendered":"

Opening a file using ‘open with’ statement and benefits in Python.<\/h2>\n

In this article we will discuss about how to open a file using ‘open with’ statement, how to open multiple files in a single ‘open with’ statement and finally its benefits. So, let’s start the topic.<\/p>\n

The need for \u201copen with\u201d statement :<\/h3>\n

To understand the \u201copen with\u201d statement we have to go through opening a file in python. For that we can make use of the open( )<\/code> function that is in-built in python<\/p>\n

File.txt-<\/strong><\/p>\n

New File Being Read.\r\nDONE!!<\/pre>\n
#program :\r\n\r\n# opened a file \r\nfileObj = open('file.txt')\r\n# Reading the file content into a placeholder\r\ndata = fileObj.read()\r\n# print file content\r\nprint(data)\r\n#close the file\r\nfileObj.close()\r\n<\/pre>\n
Output :\r\nNew File Being Read.\r\nDONE!!<\/pre>\n

In case the file does not exist it will throw a FileNotFoundError<\/code> .<\/p>\n

How to open a file using \u201copen with\u201d statement in python :<\/h3>\n
#Program :\r\n\r\n# opened a file using open-with\r\nwith open('file.txt', \"r\") as fileObj:\r\n    # Reading the file content into a placeholder\r\n    data = fileObj.read()\r\n    # print file content\r\n    print(data)\r\n# Check if file is closed\r\nif fileObj.closed == False:\r\n    print('File is not closed')\r\nelse:\r\n    print('File is already closed')\r\n<\/pre>\n
New File Being Read.\r\nDONE!!\r\nFile is closed\r\n<\/pre>\n

The with<\/code> statements created an execution block that will automatically delete any object that was created in the program, in this case even if it was not closed the reader object was deleted that closed the file automatically. This saves us some memory in case we forgot to close the file.<\/p>\n

Benefits of calling open() using \u201cwith statement\u201d :<\/h3>\n