import os from subprocess import Popen, PIPE def getFolderSize(folder): total_size = os.path.getsize(folder) for item in os.listdir(folder): itempath = os.path.join(folder, item) if os.path.isfile(itempath): total_size += os.path.getsize(itempath) if os.path.isdir(itempath): total_size += getFolderSize(itempath) return total_size def compress(output_file, directory): process = Popen(["C:/Program Files/7-Zip/7z.exe", "a", output_file, directory+os.path.sep+"*", "-mx9", "-aoa"], stdout=PIPE) process.communicate() exit_code = process.wait() if (exit_code != 0): print ("Copression of " + directory + " failed") else: print ("Copressed " + directory + " to " + output_file) rootdir = "C:/temp/test/" for root,dirs,files in os.walk(rootdir, topdown=True): depth = root[len(rootdir) + len(os.path.sep):].count(os.path.sep) if depth > 3: dirs[:] = [] # Don't recurse any deeper continue for dir in dirs: if "archive" in dir: path = os.path.join(root, dir) size = getFolderSize(path) print (path, size) if len(os.listdir(path) ) != 0: compress(root + os.path.sep + "archive.7z", path)