在 Python 的“with”语句中使用 if-else

ire*_*ene 3 python

我想打开一个可能已压缩或未压缩的文件。要打开文件,我使用

with open(myfile, 'r') as f:
    some_func(f) # arbitrary function
Run Code Online (Sandbox Code Playgroud)

或者

import gzip
with gzip.open(myfile, 'r') as f:
    some_func(f)
Run Code Online (Sandbox Code Playgroud)

我想检查是否myfilegz扩展名,然后从那里决定with使用哪个语句。这是我所拥有的:

# myfile_gzipped is a Boolean variable that tells me whether it's gzipped or not
if myfile_gzipped:
    with gzip.open(myfile, 'rb') as f:
       some_func(f)
else:
    with open(myfile, 'r') as f:
       some_func(f)
Run Code Online (Sandbox Code Playgroud)

我应该如何处理而不需要重复some_func(f)

Ama*_*dan 6

if myfile_gzipped:
    f = gzip.open(myfile, 'rb')
else:
    f = open(myfile, 'r')
with f:
    some_func(f)
Run Code Online (Sandbox Code Playgroud)

open和的结果gzip.open是一个上下文管理器。with调用上下文管理器上的进入和退出方法。在语句本身内调用这些函数没有什么特别的with