python ---- Linux压缩某个目录但要跳过指定文件

需求描述

现在Linux上有一个目录,但此目录下嵌套了许多了目录,子目录下又嵌套了许多目录,手动查看根本查看不过来,且子目录下的每个目录中都会有部分
不需要压缩的文件,忽略掉这些文件来压缩一个目录;

代码如下:

#!/usr/bin/python2.6
#-*-:coding:utf-8
import os
import sys
import re
path='/data/download'
compress={}
exclude={}
file_list = []
exclude_list = []
compress_name='/tmp/test.tar.gz'
# 要忽略的文件正则表达式匹配(忽略one-V开头并且.zip结尾的所有文件,后面同理)
regexp_rule="one-V.*.zip|two-.*.zip|three-.*.zip|four-.*.zip|five.*.zip|sdk.*.zip"
def lst_dir(x):
        dirs = os.listdir(x)
        for dir in dirs:
		check = re.search(regexp_rule,dir)
		if check:
			if check.group() == 'test-v5.6.9.7.zip' or check.group() == 'gsKtest2-v2.9.zip':
				file_list.append(os.path.join(x,dir))
			else:
                        	exclude_list.append(os.path.join(x,dir))
		elif os.path.isfile(os.path.join(x,dir)):
			file_list.append(os.path.join(x,dir))
                elif os.path.isdir(os.path.join(x,dir)):
                        dir_res = lst_dir(os.path.join(x,dir))
			#if not dir_res:
			#	file_list.append(os.path.join(x,dir))
                else:
		    pass

def exclude_file(x):
	x = str(x)
	x = x.replace("'",'')
	x = re.sub("[|]|,",'',x)
	return x

if __name__ == '__main__':
        lst_dir(path)
	new_compress=[]
	exclu_file=[]
	new_exclu=[]

	# 忽略的文件
	exclude_files = []
	for exc_file in exclude_list:
		exclude_files.append('--exclude %s' % exc_file)
	exclude_files = exclude_file(exclude_files)
	
	# 要压缩的文件
	result = os.popen("tar czvf /tmp/test.tar.gz /data/download %s ;echo $?" % exclude_files)
原文地址:https://www.cnblogs.com/k-free-bolg/p/14631941.html