没有其他优势
with:确保清理是唯一的目的。
无论如何,您都需要一个作用域块,以便在发生异常时关闭文件:
writefile = random.choice([True, False])f = open(filename) if writefile else Nonetry: # some pre or otherfinally: if writefile: f.close()
因此,
with无论您如何编写,描述为的缺点实际上是正确代码的缺点(在需要清除的情况下)。

没有其他优势
with:确保清理是唯一的目的。
无论如何,您都需要一个作用域块,以便在发生异常时关闭文件:
writefile = random.choice([True, False])f = open(filename) if writefile else Nonetry: # some pre or otherfinally: if writefile: f.close()
因此,
with无论您如何编写,描述为的缺点实际上是正确代码的缺点(在需要清除的情况下)。