Skip to content

Instantly share code, notes, and snippets.

@theriverman
Created November 11, 2020 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theriverman/38018f2fbf69fee1daf5dbbf6524431b to your computer and use it in GitHub Desktop.
Save theriverman/38018f2fbf69fee1daf5dbbf6524431b to your computer and use it in GitHub Desktop.
Copy Between ZIP Files with Python
import os
import os.path
from pathlib import Path
import zipfile
"""
ZIP_Alpha.zip and ZIP_Beta.zip contain the following files respectively.
./demo/
├── ZIP_Alpha -> ZIP_Alpha.zip
│ ├── A.txt
│ ├── B.txt
│ └── C.txt
└── ZIP_Beta -> ZIP_Beta.zip
├── docs
│ └── readme.md
├── D.txt
├── E.txt
└── F.txt
3 directories, 7 files
"""
ZIP_Root = Path(r'/tmp/demo')
ZIP_Alpha = ZIP_Root / 'ZIP_Alpha.zip'
ZIP_Beta = ZIP_Root / 'ZIP_Beta.zip'
def copy_from_zip_to_zip(source_zip: os.PathLike, target_zip: os.PathLike, skip_existing=True):
with zipfile.ZipFile(source_zip, 'r') as source_archive:
with zipfile.ZipFile(target_zip, 'a') as target_archive:
for file in source_archive.infolist():
if skip_existing and zipfile.Path(target_archive, file.filename).exists():
print(f"File '{file.filename}' already exists in target archive. Skipping...")
else:
target_archive.writestr(file, source_archive.open(file).read())
if __name__ == '__main__':
copy_from_zip_to_zip(ZIP_Beta, ZIP_Alpha)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment