Often, when someone submits their code, people will add to the side that "you must use the syntax with open('filename') as f." I agree that most old-fashioned statements f = open()do not have an accompanying one .close(), and I even answered questions where this dependence on “implicit closure” was the whole reason for their programming problem.
However, in some cases, embedded code inside a block withcreates other inconveniences when writing code. For example, I sometimes like to use the flag at the beginning to say writefile = True. This allows me to open and close the file if it will be used, while maintaining the same processing flow. In different places in the code, I can either print on the screen or write to a file. (I understand that I would open stdouteither the file at the beginning and use this approach.)
My question: Also, there is no need to explicitly close the file, are there any other reasons to use the syntax withto process the files , especially the output files? ("More pythons" is not a cause in itself.) If it is a duplicate, I would be glad if it were indicated, but I could not find it myself.
beroe source
share