Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursively unzipping a folder with ZipFile/Python

I am trying to write a script which can unzip something like this:

  • Great grandfather.zip
    • Grandfather.zip
      • Father.zip
        • Child.txt

What I have so far:

from os import listdir
import os
from zipfile import ZipFile, is_zipfile

#Current Directory  
mypath = '.'


def extractor(path):
    for file in listdir(path):
        if(is_zipfile(file)):
            print(file)
            with ZipFile(file,'r') as zipObj:
                path = os.path.splitext(file)[0]
                zipObj.extractall(path)
                extractor(path)

extractor(mypath)

I can unzip great grandfather and when I call the extractor again with grandfather as path. It doesn’t go inside the if statement. Even though, I can list the contents of grandfather.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Replace extractor(path) by these two lines:

  • os.chdir(path)
  • extractor('.')

So your code becomes:

from os import listdir
import os
from zipfile import ZipFile, is_zipfile

#Current Directory  
mypath = '.'


def extractor(path):
    for file in listdir(path):
        if(is_zipfile(file)):
            print(file)
            with ZipFile(file,'r') as zipObj:
                path = os.path.splitext(file)[0]
                zipObj.extractall(path)
                os.chdir(path)
                extractor('.')

extractor(mypath)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading