在linux中批量解压tar.gz的脚本

该脚本使用Python实现,功能是遍历指定目录下的所有.tar.gz文件,并将其解压到另一个目录。在解压过程中,为避免文件名冲突,会根据时间创建新的目标目录。使用了tar命令的--strip-components选项来去除源文件的目录结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 目标:将目录中所有.tar.gz文件解压到另一个目录

# -*- coding: utf-8 -*-
# !/usr/bin/python
import os
import time

def untar(source_path,dest_path):
    if not os.path.isdir(dest_path):
        os.mkdir(dest_path)
    path_lists = os.listdir(source_path)

    #print(path_lists)
    for file_list in path_lists:
        file_path = os.path.join(source_path,file_list)

        if file_list.endswith("tar.gz"):
            # 为了防止文件压缩过程中重命名导致解压出来的文件名与压缩包名不一致
            # 需要重新创建目录接受解压出来的文件并去到解压出来文件的一级结构
            dest_file_path = os.path.join(dest_path, file_list[:-7])
            if not os.path.exists(dest_file_path):
                os.system("mkdir -p {}".format(dest_file_path))
            else:
                os.system("mkdir -p {}".format(dest_file_path+'_exist_'+str(time.time()).replace('.','')))
            os.system("tar -zxvf {}  -C {} --strip-components 1".format(file_path,dest_file_path))



if __name__ == '__main__':
    #获取当前文件路径
    path_now = os.path.dirname(os.path.abspath(__file__))
    source_path = r"/home/tar"
    dest_path = r"/home/untar"
    untar(source_path, dest_path )






--strip-components N 去除目录结构

如: 压缩文件eg.tar 中文件信息为 src/src/src/eg.txt

运行 tar -xvf eg.tar --strip-components 1

结果:src/src/eg.txt

如果运行 tar -xvf eg.tar --strip-components 3

解压结果为: eg.txt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值