Skip to content

Instantly share code, notes, and snippets.

@pokk
Created July 28, 2017 02:50
Show Gist options
  • Save pokk/471e3bc42a969f8ac5e2b22839096e40 to your computer and use it in GitHub Desktop.
Save pokk/471e3bc42a969f8ac5e2b22839096e40 to your computer and use it in GitHub Desktop.
zip and unzip

Zip

def zip_files(src_path, dst_path_with_filename='zipfile.zip'):
    """
    :param src_path: a list of the files you want to zip.
    :param dst_path_with_filename: the destination path with file name of the zip file.
    :return: None
    """

    with zipfile.ZipFile(dst_path_with_filename, 'w', zipfile.ZIP_DEFLATED) as zf:
        for path in src_path:
            for root, dirs, files in os.walk(os.path.expanduser(path)):
                for file in files:
                    # Related path.
                    zf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '../..')))



# Example
zip_files(['~/Downloads/aa', '~/Downloads/bb', '~/Workspace/note'], os.path.expanduser('~/Downloads/cool.zip'))

Unzip

def unzip_files(zipfile_path, dst_path):
    with zipfile.ZipFile(os.path.expanduser(zipfile_path), 'r') as zf:
        zf.extractall(os.path.expanduser(dst_path))

# Example
unzip_files('~/Downloads/cool.zip', '/')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment