Why is my zip file not the same size as the zip file I'm trying to copy?

98 Views Asked by At

I'm writing a python script to append files from an old jar file to the a new jar file, but the file size of the new file isn't exactly the same as the original file. The original.jar is 6,786 KB and the patched.jar is 6,773 KB. Before running script I deleted the patched.jar file.

import zipfile

zin = zipfile.ZipFile("original.jar")
zout = zipfile.ZipFile("patched.jar", 'a')

for entry in zin.infolist():
    buffer = zin.read(entry.filename)
    zout.writestr(entry, buffer)

I need the size to be exactly the same because they are jar files and don't need compression but I didn't find any solution. Is there anything I can do to get the new file to have the same size as the old file?

Edit: It wasn't because of compression! One of the comments mentioned it was metadata and in 7zip I noticed that the original archive has files with Characteristics set to Descriptor UTF8 while original has none.

1

There are 1 best solutions below

2
Alireza On

It's probably because you don't set the compression type!

Try this code...

Method.1:

import zipfile

zin = zipfile.ZipFile("original.jar")
zout = zipfile.ZipFile("patched.jar", 'w', zipfile.ZIP_STORED, compresslevel=0)

for entry in zin.infolist():
    buffer = zin.read(entry.filename)
    zout.writestr(entry, buffer)

Method.2:

import zipfile

zin = zipfile.ZipFile("original.jar")
zout = zipfile.ZipFile("patched.jar", 'w', zipfile.ZIP_DEFLATED, compresslevel=0)

for entry in zin.infolist():
    buffer = zin.read(entry.filename)
    zout.writestr(entry, buffer)