There's no other advantage of with
: ensuring cleanup is the only thing it's for.
You need a scoped block anyway in order to close the file in the event of an exception:
writefile = random.choice([True, False])
f = open(filename) if writefile else None
try:
# some code or other
finally:
if writefile:
f.close()
So, the thing you describe as a disadvantage of with
is really a disadvantage of correct code (in the case where cleanup is required), no matter how you write it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…