就一个"with open file as f",根据条件

Just one "with open file as f", based on a conditional

我正在构建一个需要打开两种类型文件(纯文本文件和 .gz 文件)的函数

我想使用条件语句,这样我就可以只使用一个“with open”语句,而不用重复代码。

这就是我想要实现的(但显然它不能编译)

if ".gz" in f:  # gzipped version of the file, we need gzip.open
    with gzip.open(f, "rt") as file:
else:
    with open(f,"rt") as file: # normal open

for line in file: # processing of the lines of the file
    ...

我希望能够只使用一个打开,而不是必须创建两个“with open”语句和两个“for line in file

原因:我想要尽可能少的代码。

如何以 Pythonic 方式完成?

我会像这样打开(根据您的文件名将 open()gzip.open() 函数分配给变量):

import gzip

f = 'myfile.gz'
opener = open

if ".gz" in f:  # gzipped version of the file, we need gzip.open
    opener = gzip.open

with opener(f, "rt") as file:
    pass # your code