with as statement in Python

In"Input of Files in Python" mentioned that after completing the writing of the file, it must be closed through the close() method Already opened files, so as to ensure the correctness of subsequent file operations.

1 Impact of unclosed files

There is a file called "text.txt" and the content in the file is "Hello Python!". Next, change the content in the file to "I LOVE PYTHON." The code is as follows.

file = open('text.txt', 'w')
file.write('I LOVE PYTHON.')
file.close()

If after writing through the write() method, the close() method is not called to close the file, that is, only the first two lines of the above code are retained. After the code is executed, the text.txt file is opened, and the previous The content has been cleared, but new content has not been written. In other words, the write() method failed to execute.

2 with as statement

In programming file operations, we often forget to call the close() method. Through the with as statement, the file can be written without explicitly calling the close() method.

2.1 Format of with as statement

The format of the with as statement is as follows.

with 表达式 as 变量:
    语句

2.2 Execution process of with as statement

The with as statement first executes the "expression", then saves the return value of the expression to the "variable", and finally executes the "statement". The special point of the with as statement is that when the "statement" is executed, the content of the object saved in the "variable" will be automatically released, that is, the final action will be automatically completed.

2.3 Use of with as statement

You can close the file through the with as statement without explicitly calling close() to complete the writing action. The code is as follows.

with open('text.txt', 'w') as file:
    file.write('I LOVE PYTHON.')

As can be seen from the above code, although the call to close() is not shown, when the code of the with as statement is executed, the close() method will be automatically called to release the open file.

Guess you like

Origin blog.csdn.net/hou09tian/article/details/133696728