这比原来的问题更进一步。
提供从根文件夹中选择要压缩的目录的选项,以及排除所选目录中的子目录和文件的选项。
import os
import zipfile
def zipSelectExclude(src, dst, incluDIR1, incluDIR2, incluDIR3, excluSUBDIR1a, excluSUBDIR1b, excluSUBDIR3a, excluFILE3):
zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
for dirname, subdirs, files in os.walk(src):
for filename in files:
absname = os.path.abspath(os.path.join(dirname, filename))
arcname = absname[len(abs_src) + 1:]
print 'zipping %s as %s' % (os.path.join(dirname, filename),
arcname)
if incluDIR1 in dirname and excluSUBDIR1a not in dirname and excluSUBDIR1b not in dirname or incluDIR2 in dirname or incluDIR3 in dirname and excluSUBDIR3a not in dirname and excluFILE3 not in filename:
zf.write(absname, arcname),
zf.close()
""" Got the above from https://stackoverflow.com/questions/27991745/python-zip-file-and-avoid-directory-structure (answer from user 12321)
and added the 'if' statement (and the 'def' modifications) to include selected folders from root folder to zip and exclude subdirs and files.
Be careful with the 'if' statement hierarchical order - for each folder inclusion 'in dirname' specify it's subdirectories and file exclusion
with 'and ... not in dirname' nx"""
def zipSE():
src = os.path.join('/PATH/TO/MY', 'rootFOLDER')
dst = os.path.join('/PATH/TO/SAVE/MY', 'ZIPfile')
incluDIR1 = os.path.join(src, 'incluDIR1')
incluDIR2 = os.path.join(src, 'incluDIR2')
incluDIR3 = os.path.join(src, 'incluDIR3')
excluSUBDIR1a = os.path.join(incluDIR1, 'excluSUBDIR1a')
excluSUBDIR1b = os.path.join(incluDIR1, 'excluSUBDIR1b')
excluSUBDIR3a = os.path.join(incluDIR3, 'excluSUBDIR3a')
zipSelectExclude(src, dst, incluDIR1, incluDIR2, incluDIR3, excluSUBDIR1a, excluSUBDIR1b, excluSUBDIR3a, 'excluFILE3')
zipSE()