base64 encode a zip file in Python
Asked Answered
R

2

12

Can someone give me some advice on how to encode a zip file into base64 in Python? There are examples on how to encode files in Python using the module base64, but I have not found any resources on zipfile encoding.

Thanks.

Radmen answered 16/7, 2012 at 20:2 Comment(2)
Zip the file then open the file stream and run it through a b64encoder or if you want to b64 the file before hand then do the b64 then zip this b64 string.Toni
How would base64 encoding a zip file be different from base64 encoding any other file?Saddle
R
25

This is no different than encoding any other file...

import base64

with open('input.zip', 'rb') as fin, open('output.zip.b64', 'w') as fout:
    base64.encode(fin, fout)

NB: This avoids reading the file into memory to encode it, so should be more efficient.

Regnal answered 16/7, 2012 at 20:11 Comment(4)
Thanks, I don't know why I thought zip files were any different.Radmen
Should be noted that support for multiple context expressions as shown wasn't added until Py 2.7.Parotid
Note: For Python 3.x you'll need to open the output file in binary mode: open('output.zip.b64', 'wb') otherwise you'll get an error like "argument must be str, not bytes"Hubie
cool, I didn't know python can have 2 open commands in one single line, someone can explain for why is this memory efficient?Solitary
C
15
import base64

with open("some_file.zip", "rb") as f:
    bytes = f.read()
    encoded = base64.b64encode(bytes)
Contextual answered 16/7, 2012 at 20:6 Comment(2)
I like the accepted answer better than my own, because my answer reads in all the data into memory before doing the encoding.Contextual
I want to send the zip-content as base64 over the Internet, so for me this solution suits better, as it doesn't store it on disk unnecessarily and at the same time I have it in memory. After the above code I use encoded.decode('utf-8') to get the base64 string instead of the base64 bytes.Consummation

© 2022 - 2024 — McMap. All rights reserved.