Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python how to append to file in zip archive

If I do something like this:

from zipfile import ZipFile 

zip = ZipFile(archive, "a")  

for x in range(5):
    zip.writestr("file1.txt", "blabla")

It will create an archive with 5 files all named "file1.txt". What I want to achieve is having one compressed file to which every loop iteration appends some content. Is it possible without having some kind of auxiliary buffer and how to do this?

like image 293
mnowotka Avatar asked Mar 13 '12 08:03

mnowotka


2 Answers

It's impossible with zipfile package but writing to compressed files is supported in gzip:

import gzip
content = "Lots of content here"
f = gzip.open('/home/joe/file.txt.gz', 'wb')
f.write(content)
f.close()
like image 145
Lev Levitsky Avatar answered Nov 12 '22 09:11

Lev Levitsky


Its quite possible to append files to compressed archive using Python.

Tested on linux mint 14,Python 2.7

import zipfile

#Create compressed zip archive and add files
z = zipfile.ZipFile("myzip.zip", "w",zipfile.ZIP_DEFLATED)
z.write("file1.ext")
z.write("file2.ext")
z.printdir()
z.close()

#Append files to compressed archive
z = zipfile.ZipFile("myzip.zip", "a",zipfile.ZIP_DEFLATED)
z.write("file3.ext")
z.printdir()
z.close()

#Extract all files in archive
z = zipfile.ZipFile("myzip.zip", "r",zipfile.ZIP_DEFLATED)
z.extractall("mydir")
z.close()
like image 11
Ryu_hayabusa Avatar answered Nov 12 '22 09:11

Ryu_hayabusa