【发布时间】:2021-10-14 08:40:12
【问题描述】:
而不是这个:
FILE = open(f)
do_something(FILE)
FILE.close()
最好用这个:
with open(f) as FILE:
do_something(FILE)
如果我有这样的东西怎么办?
if f is not None:
FILE = open(f)
else:
FILE = None
do_something(FILE)
if FILE is not None:
FILE.close()
do_something 也有一个“if FILE is None”子句,并且在这种情况下仍然会做一些有用的事情 - 我不只想跳过 do_something 如果 FILE 是 None。
有没有一种明智的方法可以将其转换为 with/as 形式?还是我只是试图以错误的方式解决可选文件问题?
【问题讨论】:
标签: python file-io with-statement