Skip to content
Advertisement

Exclude a directory from getting zipped using zipfile module in python

I am trying to zip a directory using python zipfile module and its working well.But now i want to exclude some folders.ie if my director tree is like

abc
def
ghi
jkl
mno

then i want to archive all to myfile.zip but excluding “ghi”

I am trying to zip files using

zf = zipfile.ZipFile("Application server.zip", "w")
for dirname, subdirs, files in os.walk("D:\review docs"):
    zf.write(dirname)
    for filename in files:
        zf.write(os.path.join(dirname, filename))
zf.close()

so this is archiving everything under “D:review docs” to “Application server.zip” but i want to exclude some directories from the zip. In fact i can use linux commands to do the same but i want to use zipfile module. Also if i pop exclude folder name from “dirname” list optained from os.walk,will that work? further Adding up a check before zipping like if “dirname”==”exlude folder” will also work i think but i want a neat solution of doing the same using the module.I read some where that zipfile module provides this functionality but didn’t found any code example for the same.

Advertisement

Answer

Yes , you can remove elements from the subdirs , that would make sure that os.walk() does not into those directories. Example –

for dirname, subdirs, files in os.walk("D:\review docs"):
    if 'exclude directory' in subdirs:
        subdirs.remove('exclude directory')
    zf.write(dirname)
    for filename in files:
        zf.write(os.path.join(dirname, filename))
zf.close()
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement