根据文件扩展名打开语句

时间:2018-03-11 19:49:39

标签: python python-3.x

我需要在目录中处理两种类型的文件 - print.txt。 为此目的有两种类型的开放语句:

.gz 文件:

.gz

.txt 文件:

with gzip.open(file_name, 'rt', encoding='utf-8') as f:
    line = next(f)
    while line:
        some code

任何进一步的处理命令都完全相同。现在我看到两种处理这两种文件类型的选项:

选项1 - 使用两个仅由with open(file_name, 'r', encoding='utf-8') as f: line = next(f) while line: some code 语句不同的相同函数。听起来很难看......

选项2 - 使用open构造如下:

if

但它对我来说仍然很尴尬:/

问题:Python 3.x中的pythonic方法是根据文件扩展名使用open语句?

3 个答案:

答案 0 :(得分:2)

为什么不:

with (gzip.open if ext==".gz" else open)(file_name, 'rt', encoding='utf-8') as f:

with的第一个参数是三元表达式,您可以根据扩展名决定使用哪个函数。我在两种情况下都使用'rt',它是标准open的默认值。该方法的优点是避免复制/粘贴,并且能够使用上下文管理器。

也许可以使用辅助函数创建一些泛型函数:

def myopen(file_name)
  return (gzip.open if os.path.splitext(file_name)[1]==".gz" else open)(file_name, 'rt', encoding='utf-8')

使用像:

with myopen(file_name):

答案 1 :(得分:0)

另一种方法是使用扩展名为{/ 1>的defaultdict

from collections import defaultdict
from pathlib import Path

open_functions = defaultdict(lambda: (open, ("r",), {encoding: "utf-8"}))
open_functions["gz"] = (gzip.open, ("rt",), {encoding: "utf-8"})

filename = Path(filename)

open_function, args, kwargs = open_functions[filename.suffix]
with open_function(filename, *args, **kwargs) as f:
    ...

答案 2 :(得分:-1)

我想建议以下方式:

#------------------------------------
import zipfile

#-----------------------Common Code-------------------------
def disp_line(filee):    
        for line in filee.readlines():    
            print(line)

#-----------------------First File-----------------------  
z = zipfile.ZipFile('D:\\DC-Data\\baby_names.zip', "r")    
zinfo = z.namelist()    
for name in zinfo:    
    with z.open(name) as filee:    
        disp_line(filee)

#-----------------------2nd File-------------------------            
with open('D:\\DC-Data\\iris.txt', 'r') as filee:
    disp_line(filee) 

#------------------------End ----------------------