Search code examples
pythonfilejaradditionpython-zipfile

Add a file to a jar using python zipfile


I need to add a file to jar but when i run the program zipfile delete all file and add a file. but i need the other files!

my code: (this is a test)

import zipfile
    
m= zipfile.ZipFile("test.jar","w")
m.write("test.jar","bgt.class")
m.close()

Solution

  • You need to open the file in append mode, using a:

    m = zipfile.ZipFile("test.jar", "a")
    

    You opened the file in w write mode, which clears the file before writing. From the zipfile.ZipFile() documentation:

    The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, or 'a' to append to an existing file. If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it.

    Bold emphasis mine.