How to compress files to create a new ZIP archive in Python

Creating ZIP archives in Python has always been a struggle. That is, until today. I am about to slice through that particular Gordian knot with a well-placed API.

Before anything else, pip install the API client that we need:

pip install cloudmersive-convert-api-client

Now it’s time that we wrote up our function call. This example code will get you started:

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom cloudmersive_convert_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.ZipArchiveApi(cloudmersive_convert_api_client.ApiClient(configuration))request = cloudmersive_convert_api_client.CreateZipArchiveRequest() # CreateZipArchiveRequest | Input requesttry:# Compress files and folders to create a new zip archive with advanced optionsapi_response = api_instance.zip_archive_zip_create_advanced(request)pprint(api_response)except ApiException as e:print("Exception when calling ZipArchiveApi->zip_archive_zip_create_advanced: %s\n" % e)

Our function is going to need its request object, which we can fill out like this:

{
"FilesInZip": [
{
"FileName": "string",
"FileContents": "string"
}
],
"DirectoriesInZip": [
{
"DirectoryName": "string",
"DirectoriesInDirectory": [
null
],
"FilesInDirectory": [
{
"FileName": "string",
"FileContents": "string"
}
]
}
]
}

Now send the request and in a few moments you will have your newly created zip archive. Talk about easy! For an even simpler approach with less customization, you can also use zip_archive_zip_create.

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store