pythonzipdirectoryshutil

Zip File with Python Shutil like File Explorer


Background

I am trying to zip a directory with python shutil like this:

shutil.make_archive("~/Desktop/zipfile", 'zip', "~/Documents/foldertozip")

but the result only zips the files inside "foldertozip". So for instance,

foldertozip
    -- file1
    -- file2
zipfile.zip
    -- file1
    -- file2

On the other hand, if I zip it from windows file explorer or mac finder, I get the following:

foldertozip
    -- file1
    -- file2
zipfile.zip
    -- foldertozip
        -- file1
        -- file2

Question

How can I use shutil to do the same thing that I could do from a file explorer and include the base directory? I know I could copy "foldertozip" to a folder with the same name and then zip that folder, but I would prefer a cleaner solution if at all possible.


Solution

  • make_archive will do what you want if you pass both root_dir and base_dir. See the docs.

    import shutil
    
    shutil.make_archive('~/Desktop/zipfile', 'zip', '~/Documents/', 'foldertozip')