一个上下文管理器而不是两个用于打开文件?
One context manager instead of two for open file?
我的问题看起来与 类似,但不确定...我想解析一些有时用 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
语句?
把你的"Do Something"放在一个函数中
def processFile(f)
Do Something...
if file[-3:] == ".gz":
with gzip.open(file, 'rb') as f:
processFile(f)
else:
with open(file) as f:
processFile(f)
fn = gzip.open if file.endswith('.gz') else open
with fn(file, 'rb') as f:
...
另请注意,调用返回上下文管理器的函数不必发生在 with
行内:
if file.endswith('.gz'):
ctx = gzip.open(file, 'rb')
else:
ctx = open(file)
with ctx as f:
...
你可以把条件语句放在with
行:
with gzip.open(file, 'rb') if file[-3:] == '.gz' else open(file) as f:
processFile(f)
我的问题看起来与
我有以下内容:
if file[-3:] == ".gz":
with gzip.open(file, 'rb') as f:
# do something
else:
with open(file) as f:
# do the same thing.
是否可以只有一个 with
语句?
把你的"Do Something"放在一个函数中
def processFile(f)
Do Something...
if file[-3:] == ".gz":
with gzip.open(file, 'rb') as f:
processFile(f)
else:
with open(file) as f:
processFile(f)
fn = gzip.open if file.endswith('.gz') else open
with fn(file, 'rb') as f:
...
另请注意,调用返回上下文管理器的函数不必发生在 with
行内:
if file.endswith('.gz'):
ctx = gzip.open(file, 'rb')
else:
ctx = open(file)
with ctx as f:
...
你可以把条件语句放在with
行:
with gzip.open(file, 'rb') if file[-3:] == '.gz' else open(file) as f:
processFile(f)