now available
Want fresh tech tips in your inbox?

How to Use Python Shutil Make_Archive to Zip Up a Directory Recursively including The Root Folder


The documentation for Python's shutil.make_archive is very confusing. Considering that the arguments to this function only need to be source and destination, makes it even more frustrating to try and reason about.

Here are the relevant docs from the python (2.7) website:

shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
Create an archive file (eg. zip or tar) and returns its name.

base_name is the name of the file to create, including the path, minus any format-specific extension. format is the archive format: one of “zip” (if the zlib module or external zip executable is available), “tar”, “gztar” (if the zlib module is available), or “bztar” (if the bz2 module is available).

root_dir is a directory that will be the root directory of the archive; ie. we typically chdir into root_dir before creating the archive.

base_dir is the directory where we start archiving from; ie. base_dir will be the common prefix of all files and directories in the archive.

root_dir and base_dir both default to the current directory.

On the face of it they don't seem too bad. Until you try to implement it and nothing seems to work. Took me about 20 permutations of the arguments to get right.. mostly because root_dir and base_dir can mean the exact same thing.

Talk about consfusing! Anyway, you can use the following function that I wrote to wrap shutil.make_archive into something more easy to use and understand.

It takes a folder path as the first argument and the destination of archived folder as the second argument.

import os, shutil
def make_archive(source, destination):
        base = os.path.basename(destination)
        name = base.split('.')[0]
        format = base.split('.')[1]
        archive_from = os.path.dirname(source)
        archive_to = os.path.basename(source.strip(os.sep))
        print(source, destination, archive_from, archive_to)
        shutil.make_archive(name, format, archive_from, archive_to)
        shutil.move('%s.%s'%(name,format), destination)

make_archive('/path/to/folder', '/path/to/folder.zip')
Tagged w/ #python #zip #directories #file system #recursive #shutil

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app