{"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":"
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
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 File.txt-<\/strong><\/p>\n In case the file does not exist it will throw a The With \u201cwith\u201d statement we don’t have to close the opened file manually. It takes care of that when the compiler goes out of the block and automatically closes file. So it reduces the chances of bugs, lines of code and releases the memory for other operations.<\/p>\n If we have used \u201copen-with\u201d statement to open a file, and an exception occurs inside the with block, the file will be closed and the control moves to the except block.<\/p>\n We can use open with statement to open multiple files at the same time. Let\u2019s try reading from one file and writing into another-<\/p>\n This will generate a \u201c The files will automatically close when the control moves outside the with block.<\/p>\n","protected":false},"excerpt":{"rendered":" Opening a file using ‘open with’ statement and benefits in Python. 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. The need for \u201copen with\u201d statement : To …<\/p>\nopen( )<\/code> function that is in-built in python<\/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
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
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
\n
Fewer chances of bug due to coding error<\/h4>\n<\/li>\n<\/ul>\n
\n
Excellent handling in case of exception<\/h4>\n<\/li>\n<\/ul>\n
# Python :\r\n\r\n# Before handling the exception file\u00a0will\u00a0be\u00a0closed\u00a0\r\ntry:\r\n # using \"with statement\" with open() function\r\n with open('file.txt', \"r\") as fileObj:\r\n # reading the file content\r\n data = fileObj.read()\r\n # Division by zero error\r\n x = 1 \/ 0\r\n print(data)\r\nexcept:\r\n # handling the exception caused above\r\n print('Error occurred')\r\n if fileObj.closed == False:\r\n print('File is not closed')\r\n else:\r\n print('File is closed')\r\n<\/pre>\n
Output :\r\nError occurred\r\nFile is closed<\/pre>\n
\n
Open multiple files in a single \u201cwith statement\u201d :<\/h4>\n<\/li>\n<\/ul>\n
# Program :\r\n\r\n# Read from file.txt and write in output.txt\r\nwith open('output.txt', 'w') as fileObj2, open('file.txt', 'r') as fileObj1:\r\n data = fileObj1.read()\r\n fileObj2.write(data)\r\n # Both the files are automatically close when the control moves out of the with block.\r\n<\/pre>\n
outuput.txt<\/code>\u201d file that will have the same contents as our old \u201c
file.txt<\/code>\u201d.<\/p>\n
Output : \r\nOutput.txt- \r\nNew File Being Read. \r\nDONE !!<\/pre>\n