下面代码可以将多个文件夹压缩至同一个ZIP文件,即使这些文件夹不在同一个文件夹中,甚至不在同一个驱动器上。
from zipfile import ZipFile
from os import listdir
from os.path import isfile, isdir, join
def addFileIntoZipfile(srcDir, fp):
for subpath in listdir(srcDir):
subpath = join(srcDir, subpath)
if isfile(subpath):
fp.write(subpath)
elif isdir(subpath):
fp.write(subpath)
addFileIntoZipfile(subpath, fp)
def zipCompress(srcDir, desZipfile):
fp = ZipFile(desZipfile, mode='a')
addFileIntoZipfile(srcDir, fp)
fp.close()
paths = [r'C:\python35\Scripts', r'C:\python35\Dlls', r'D:\tc']
for path in paths:
zipCompress(path, 'test.zip')