[Python] What is a with statement?
[Python] What is a with statement? Explain the usage and meaning with actual examples
With is used in the explanation of ExcelWriter,
I investigated the meaning and usage, so I summarized it.
・ Official page (overview)
・ Official page (example)
## Use and content of the with statement
** ■ Applications **
** Used for processing that is a set of "start" and "end" **.
-Open the file to read and write.
-Access the DB and exit after processing.
** ■ Processing content **
In the process that "start" and "end" are set
If you "start" using the with statement, it will ** automatically "end" ** after the process is executed.
** ■ Merit **
-You do not have to write the termination process.
-Do not forget to write the end process.
## Basic syntax of with
```
with ① Start processing as ② Variable:
③ Processing
```
① Start processing
└ Describe the process to start communication such as opening a file.
② Variable
└ Variable (abbreviation) for calling process ①
③ Processing
└ Process to be executed. When this process is completed, the file is automatically closed (communication is disconnected).
## Code example using the with statement
In the official python documentation,
It is used in the open function that opens a file and ExcelWriter that opens Excel.
open
with open('spamspam.txt', 'w', opener=opener) as f:
print('This will be written to somedir/spamspam.txt', file=f)
Built-in function open
ExcelWriter
with ExcelWriter('path_to_file.xlsx') as writer:
df.to_excel(writer)
Official page of ExcelWriter