zip – Python: How to use shutil.make_archive?
zip – Python: How to use shutil.make_archive?
I ran into this same issue and found the docs for shutil.make_archive very dense and counter intuitive.
I eventually got it and wrote a function to help me out because I could never get it right the first time.
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))
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)
Hope it helps.. I also have a blog post about it here
The docs are not worded helpfully. If we go from the usage shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
base_name
is the path where you want to archive to be created, including the filename, but not including the extensionformat
, as you figured out, is the type of archive you want to create
You might have noticed that everything else is optional. With just those two parameters, the function will create an archive of your current working directory. Thats not what you want, so lets check out the next two parameters:
root_dir
is the directory from which you want to create an archivebase_dir
is a way to filter the contents ofroot_dir
. if you setbase_dir
, your archive will contain the parent directories ofbase_dir
going up toroot_dir
, but all other contents of those parent directories will not be present. Onlybase_dir
and its children will contain all their contents.
Since youre just trying to archive your directory as is, you dont need base_dir
. So I would just amend your original call to:
import os
#...
make_archive(os.path.join(folderpath_archive, filename), zip, folderpath_to_zip_up)