How to extract Files and Folders from a Zip Archive in Python

Zip extraction is one of those crucial features that many projects cannot live without. Despite its mundane nature, if you try to code this one out from scratch you will soon see that this is actually quite difficult to do. Let’s not spend all day on this one. Instead, let’s do it in a couple minutes and free up the rest of your afternoon!

The following command will install our API client, so we should begin with that.

pip install cloudmersive-convert-api-client

Now we can use a free API key and a newly created API instance to call our zip extraction function. Refer to the following example for the details:

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom 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))input_file = '/path/to/file' # file | Input file to perform the operation on.try:# Extract, decompress files and folders from a zip archiveapi_response = api_instance.zip_archive_zip_extract(input_file)pprint(api_response)except ApiException as e:print("Exception when calling ZipArchiveApi->zip_archive_zip_extract: %s\n" % e)

Finished! Super simple. We can also use the rest of this library to do all sorts of useful stuff, including creating our zip files to begin with.

Image for post
Image for post
No late night at the office today!

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