python how to append to file in zip archive

12,663

Solution 1

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

Solution 2

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()
Share:
12,663
mnowotka
Author by

mnowotka

Professional Python developer with many years of experience in writing code in Python and C++ and joining them together. Experienced web developer and open source enthusiast. Has academic background in CS but professionally involved in chem and bio informatics. A gentleman, who demands excellence from his code. LinkedIn Profile GitHub repo My presentations

Updated on June 08, 2022

Comments

  • mnowotka
    mnowotka almost 2 years

    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?

  • Kien Truong
    Kien Truong about 12 years
    But gzip can only contain one file.
  • Lev Levitsky
    Lev Levitsky about 12 years
    Yep, but it can be used together with tarfile or zipfile.
  • Kien Truong
    Kien Truong about 12 years
    When you use it with tar, you can not write directly to a single file like this anymore :)
  • Lev Levitsky
    Lev Levitsky about 12 years
    What I mean is that the data can be written in gzip-compressed files that are then packed into a tar archive later in the same script.
  • Jatin Kumar
    Jatin Kumar about 9 years
    There is no way one can "append" to a file in zip file using the python zipfile library. Please suggest if there is some other library which I can use to append content to a file.
  • Charles Duffy
    Charles Duffy about 6 years
    I believe the clear reading of the question is that the OP wants to append to file1.ext, adding additional content to that existing file in multiple iterations, as opposed to adding additional files.
  • Oleg Kokorin
    Oleg Kokorin over 4 years
    the question is about to append data into the same file entity inside the ZIP archive but appending another file entity into the same ZIP archive