简体   繁体   中英

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?

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()

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()

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