Search code examples
pythonbase64zip

How to base64 encode Object of type ZipFile


I have a zip file that is in memory and I would like to convert it into a base64 encoded utf-8 string for another function to parse downstream.

The file is created as follows

data = BytesIO()
zip = zipfile.ZipFile(data, 'w')
zip.writestr(test.csv, 'Hello world')
zip.close()
data.close()

b64zip = base64.b64encode(zip)

However, when trying to base64 encode the zip file I get the following error:

a bytes-like object is required, not 'ZipFile'

How can I convert this ZipFile object into a base64 encoded string?


Solution

  • Zip files are byte encoded so use:

    zip = zipfile.ZipFile(data, 'rb')