我想把二进制数据写入zip文件。
以下情况有效,但如果我尝试将.zip
作为文件扩展名添加到变量x
中的“检查”,则不会向该文件写入任何内容。我被困在手动添加.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)
为了在文件中附加正确的扩展名,我尝试使用模块ZipFile
with ZipFile(x, "wb") as work:
work.write(b)
但获得RuntimeError
:
RuntimeError: ZipFile() requires mode "r", "w", or "a"
如果删除b
标志,则会创建一个空的zipfile,我会得到一个TypeError
:
TypeError: must be encoded string without NULL bytes, not str
我也尝试过,但它会创建一个损坏的zip文件。
os.rename(x, z )
如何将二进制数据写入zip文件。
答案 0 :(得分:1)
您不能将数据直接写入zip文件。您将其写入文件,然后将文件路径写入zip文件。
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)
答案 1 :(得分:1)
我将zip文件转换为二进制数据,并能够通过以下方式重新生成zip文件:
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)
答案 2 :(得分:0)
使用writestr
方法。
import zipfile
z = zipfile.ZipFile(path, 'w')
z.writestr(filename, bytes)
z.close()