Frequently when someone posts their code, people will add as an aside that "you should use with open('filename') as f
syntax now." I agree that most of the old-fashioned f = open()
statements don't have an accompanying .close()
, and I have even answered questions where this reliance on "implicit close" was the entire cause of their programming problem.
However, in some cases nesting your code inside the with
block seems to create other inconveniences in writing the code. For example I sometimes like to use a flag at the beginning to say writefile = True
. This lets me only open and close the file if it is going to be used, while keeping the same processing thread. At various places in the code I can either print to screen or write to a file. (I realize I would open stdout
or the file at the beginning and use that approach instead.)
My question is: besides not having to explicitly close the file, are there other reasons to use the with
syntax for handling files, especially output files? ("More pythonic" by itself is not a reason.) If this is a duplicate, I would be glad to have this pointed out, but I couldn't find it myself.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…