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://stackoverflow.com/questions/41525690/open-file-depending-on-whether-its-gz-or-not


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM