0

Can anyone please help me to advise how to loop through a Zip file that contains child zip files (and even more sub folders in zipped format) and still maintain the folder structure after unzipping them? I want to attain this by linux script or Python 2.7 (not Python 3)

Basically, below is what I have:

ZIPPED File Structure

--CLASS1.zip

       --SUBJECT1.zip

       --SUBJECT2.zip

       --SUBJECT3.zip

       --SUBJECT4.zip



--CLASS2.zip

       --SUBJECT1.zip

       --SUBJECT2.zip

       --SUBJECT3.zip

       --SUBJECT4.zip



--CLASS3.zip

       --SUBJECT1.zip

       --SUBJECT2.zip

       --SUBJECT3.zip

       --SUBJECT4.zip

The level of zipping might go further but I gave just for illustration purpose. I want to maintain the same directory structure even after Unzipping like shown below:

--CLASS1

       --SUBJECT1

       --SUBJECT2

       --SUBJECT3

       --SUBJECT4



--CLASS2

       --SUBJECT1

       --SUBJECT2

       --SUBJECT3

       --SUBJECT4



--CLASS3

       --SUBJECT1

       --SUBJECT2

       --SUBJECT3

       --SUBJECT4

Please suggest the best possible way to attain this.

Rana
  • 1
  • 1
  • What should happen with a zip file containing itself? https://stackoverflow.com/a/3169256/1030675 – choroba Apr 07 '21 at 08:29
  • I'll check that later. You'll need to recursively go on folder you extract from your archive. Let say you extract CLASS1 folder, you'll want to list all zip under CLASS1.zip then do it again, until you don't find zip file anymore. That would be easier on python i think. You can try something but i can't help you right away :) – Vollfeiw Apr 07 '21 at 15:18
  • Also, you could check https://unix.stackexchange.com/questions/4367/extracting-nested-zip-files – Vollfeiw Apr 07 '21 at 15:26
  • In Python 3, I created the below snippet and its working but I want this to be done in Strict Python 2 and I don't know why I am unable to get that done :( – Rana Apr 08 '21 at 03:53
  • This is working Python 3 script, but need Python2: `code` import logging from pathlib import Path from shutil import unpack_archive import shutil import glob,os,re,sys zip_files = Path(unzip_dir).rglob("*.zip") while True: try: path = next(zip_files) except StopIteration: break # no more files except PermissionError: logging.exception("permission error") else: extract_dir = path.with_name(path.stem) unpack_archive(str(path), str(extract_dir), 'zip') `code` – Rana Apr 08 '21 at 04:32
  • Alternatively, I am trying in Linux: `code` find . -iname '*.zip' -exec sh -c 'unzip -o -d "${0%.*}" "$0"' '{}' ';' `code` However, running this only unzips on first level. But re-running the line again unzips all the inner zip files. This seems working but it doesn't looks good approach. Any other ideas please – Rana Apr 08 '21 at 04:36

0 Answers0