【发布时间】:2020-04-02 16:37:36
【问题描述】:
我的问题看起来类似于this one,但不确定...我想解析一些有时在 gzip 中压缩的日志文件,有时不是。
我有以下内容:
if file[-3:] == ".gz":
with gzip.open(file, 'rb') as f:
# do something
else:
with open(file) as f:
# do the same thing.
是否可以只有一个with 语句?
【问题讨论】:
-
这可能是可能的,但我认为这会更令人困惑。也许只是将
something放在一个函数中,这样你就不会重复你的代码。 -
你试过`with ... if ... else ...´吗?
标签: python python-3.x with-statement