简体   繁体   中英

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.

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)

I converted a zip file into binary data and was able to regenerate the zip file in the following way:

bin_data=b"\x0\x12" #Whatever binary data you have store in a variable
binary_file_path = 'file.zip' #Name for new zip file you want to regenerate
with open(binary_file_path, 'wb') as f:
    f.write(bin_data)

Use the writestr method.

import zipfile
z = zipfile.ZipFile(path, 'w')
z.writestr(filename, bytes)
z.close()

zipfile.ZipFile.writestr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM