Python如何支持读入gz压缩或未压缩文件?

目录

需求

要写一个接口,同时支持压缩和未压缩文件读入

示例代码

笨办法

import os
import gzip

filename = sys.argv[1]
if not filename.endswith('.gz'):
    with open(filename, 'r') as infile:
        for line in infile:
            # do something
else:
    with gzip.open(filename, 'r') as infile:
        for line in infile:
            # do something

代码一长,肯定很难看。尝试写成函数。

Pythonic方法

def openfile(filename, mode='r'):
    if filename.endswith('.gz'):
        return gzip.open(filename, mode) 
    else:
        return open(filename, mode)

with openfile(filename, 'r') as infile:
    for line in infile:
       # do something

https://*.com/questions/41525690/open-file-depending-on-whether-its-gz-or-not

上一篇:python学习 day6 (3月6日)


下一篇:something just like this