Search code examples
pythonpython-requestszip

Write Binary data with python to a zip file


I am tying to write a binary data to a zip file.

The below works but if I try to add a .zip as a file extension to "check" in the variable x nothing is written to the file. I am stuck manually adding .zip

urla = "some url"
tok = "some token"
pp = {"token": tok}
t = requests.get(urla, params=pp)
b = t.content
x = r"C:\temp" + "\check"
z = 'C:\temp\checks.zip'
with open(x, "wb") as work:
     work.write(b)

In order to have the correct extension appended to the file I attempted to use the module ZipFile

with ZipFile(x, "wb") as work:
    work.write(b)

but get a RuntimeError:

RuntimeError: ZipFile() requires mode "r", "w", or "a"

If I remove the b flag an empty zipfile is created and I get a TypeError:

TypeError: must be encoded string without NULL bytes, not str

I also tried but it creates a corrupted zipfile.

os.rename(x, z ) 

How do you write binary data to a zip file.


Solution

  • You don't write the data directly to the zip file. You write it to a file, then you write the filepath to the zip file.

    binary_file_path = '/path/to/binary/file.ext'
    with open(binary_file_path, 'wb') as f:
        f.write('BINARYDATA')
    
    zip_file_path = '/path/to/zip/file.zip'
    with ZipFile(zip_file_path, 'w') as zip_file:
        zip_file.write(binary_file_path)