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.
Comments
Post a Comment