Skip to content

Instantly share code, notes, and snippets.

@chen3feng
Last active May 30, 2020 10:40
Show Gist options
  • Save chen3feng/e9dadbf344b467457f4f8252978f1e47 to your computer and use it in GitHub Desktop.
Save chen3feng/e9dadbf344b467457f4f8252978f1e47 to your computer and use it in GitHub Desktop.
Copy files inside a zip into another zip file without uncompress it ahead, improve the speed,
#!/usr/bin/env python
"""
Copy files inside a zip into another zip file without uncompress it ahead, improve the speed,
"""
import zipfile
def zipfile_get_entry(source, name):
"""Read a file entry pair (zipinfo, zipextfile) from a zip file"""
return source.getinfo(name), source.open(name)
def zipfile_write_entry(target, zipinfo, zipextfile):
"""Direct copy the file entry from source into target without uncompression."""
# Create ZipInfo instance to store file information
zinfo = zipinfo
zinfo.header_offset = target.fp.tell() # Start of header bytes
target._writecheck(zinfo)
target._didModify = True
# Read all compressed content for source file
buf = zipextfile._fileobj.read(zipextfile._compress_size)
target.fp.write(zinfo.FileHeader())
target.fp.write(buf)
target.filelist.append(zinfo)
target.NameToInfo[zinfo.filename] = zinfo
def main():
source = zipfile.ZipFile('blade.zip', 'r')
with zipfile.ZipFile('out.zip', 'w') as out:
for name in source.namelist():
zi, ze = zipfile_get_entry(source, name)
zipfile_write_entry(out, zi, ze)
if __name__ == '__main__':
main()
@chen3feng
Copy link
Author

将zip文件中的文件复制到另一个zip文件中,而无需提前对其进行解压缩,从而提高了速度。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment