'with' keyword and files






Hello Folks....!!!
Today let us look at a hack that is very useful while using the file operations.

When you open the files using the built-in function open(), You have to explicitly close the file using the command file_object.close(). If you forget to do so, it will remain open until the whole project/program is execution state. Here, you can find the proof below.


After this, I switched to some other coding snippets and then checked whether the file is closed at the end,Look at the code snippet below.


If the file was closed, we would have got True here. So unless and until you close the file explicitly, it remains open. To overcome this issue we can use 'with' statement.

with keyword in Python

with is keyword that is used as context manager in Python. It is used to manage the resources ( like files) we use in our program. It handles the cleaning up of all the resources we utilize in the program an. It also handles the exceptions effectively and if with open() is used then try-except block is not required.

The general syntax of writing with and open() for file operations is given below:

with open(file_name, mode) as variable_name:

variable_name.operations

the variable_name can be anything. It can be a single letter even. After opening a file using this syntax wherever the file has to be accessed, the variable_name should be used to perform the operations (read/write).

Look at the example below.



The file is opened without any exception. Now look at the snippet below.



It can effectively handle the exceptions also. Now after correcting this error, the file was opened successfully and then I executed other code snippets for a while and checked whether the file remains open. 



The file has been automatically closed by the context manager. The use of this with keyword offers this advantage.


Next Topic👉

Comments