python脚本系列——遍历解压文件夹以及子目录.gz包

import gzip
import os
import shutil
import sys

"""
文件夹内全部是gzip包,一行gunzip -r也可以解决,python方式更加灵活,如下
"""

# 读取gz文件并解压
def gunzip_shutil(source_file, dest_file, block_size=65536):
    with gzip.open(source_file, 'rb') as s_file, \
            open(dest_file, 'wb') as d_file:
        shutil.copyfileobj(s_file, d_file, block_size)

# 遍历文件夹找到符合条件的结果
def loop_dir(path):
    for root, dirs, files in os.walk(path, topdown=False):
        # root路径,dirs目录,files文件,根据需求拿结果
        for name in files:
            if name.endswith('.gz'):
                fullname = os.path.join(root, name)
                # 解压方法
                gunzip_shutil(fullname, fullname[:-3])
                # 删除原来的压缩包
                os.remove(fullname)

def main(argv):
    loop_dir("E:/文件夹名称")

if __name__ == '__main__':
    main(sys.argv)

猜你喜欢

转载自blog.csdn.net/weixin_39855998/article/details/128411539
今日推荐