目标:将目录中所有.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