Is there an easy way to modify the contents of a zip file inside the archive, without unpacking everything to a temp directory, making the change, then packing it all up again?

I've got a whole bunch of zip files, each one with a bunch of plain text files (html, xml, txt) in a fussy directory structure.

My script needs to open up the zip files, and make occasional changes to the files within.

Currently the relevant part of my code goes like:

for root, dirs, files in os.walk(maindir):

    for currentfile in files:

        currentzip = zipfile.ZipFile(os.path.join(root, currentfile), mode='r')
        innernames = currentzip.namelist()

        for name in innernames:
            filecontent = currentzip.read(name)

            #Do stuff here to modify filecontent.

            #And now I'd like to simply write filecontent back to the zip file,
            #replacing the content of the file "name" that's in "currentzip" without
            #changing its directory info or other info in the archive.

I guess I could rewrite my code to unpack each zip file, then re-pack it when I'm done, but I don't want to do that if a more elegant and efficient solution exists. The number of files involved is high enough that efficiency matters.

Thanks!

Thanks for the reply. That might work, using something like subprocess.Popen("zip stuffgoeshere", shell=True) to change the files I need.

Except I couldn't do that while the file was still open with zipfile, which would mean I'd have to log all the changes to all the files I'd want to make in each archive, close zipfile, then open the archive file again with subprocess.Popen.

Unfortunately, I'm trying to make this work independent of the operating system, and also work "out of the box" (I can't assume a windows user has 7zip installed).

I wonder if there's a way to do this just with zipfile?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.