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?
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With