首页 > 编程语言 > 详细

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

时间:2021-03-15 19:23:25      阅读:38      评论:0      收藏:0      [点我收藏+]

需求

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

示例代码

笨办法

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

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

原文:https://www.cnblogs.com/jessepeng/p/14538357.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!