Unzip zip files in folders and subfolders with python

16504
7
02-05-2015 02:27 AM
Yaron_YosefCohen
Occasional Contributor II

Hello everyone,

I try to unzip 150  zip files which contain shapefiles. All the zip files as different names, and they all spread in one big folder that divided to a lot of sub folders and sub sub folders.i want to extract each archive to separate folder with the same name as the original zip file name and also in the same place as the original zip file . I'm working with arcview 10.3 and my code is:

import zipfile  
import arcpy,os,os.path,sys
from arcpy import env

pattern = '*.zip'
folder = r"C:\Project\layers" 
files_process = []
for root,dirs,files in os.walk(r"C:\Project\layers"):
    for filenames in files:
        if filenames == pattern:
            files_process.append(os.path.join(root, filenames))
            zip.extract()

After i run the code nothing happened.

Thanks in advance for any help on this.

Tags (2)
0 Kudos
7 Replies
DanPatterson_Retired
MVP Emeritus

I am confused...in your last line, you told Python to print 'zip' ... which it will do multiple times ... so as not to ruin the mystery...I assume that you wanted to have the zip file being printed rather than the word 'zip'

0 Kudos
Yaron_YosefCohen
Occasional Contributor II

thanks Dan i will change it now.

0 Kudos
DanPatterson_Retired
MVP Emeritus

All you did in this thread arcpy - Unzip files in folders and subfolders with python - Geographic Information Systems Stack Exc...  is simply remove the print statement...now nothing prints...as suggested there...did anything happen? did you explore the folders to see if anything was output?  If you did, then report the problem

UPDATE

this line

print 'unzip'

was originally

print 'zip'

progress is being made

0 Kudos
Yaron_YosefCohen
Occasional Contributor II

i checked all folders- nothing happend

0 Kudos
DanPatterson_Retired
MVP Emeritus

import os # needs to be added

os.listdir('c:/temp')  # to print files in a folder

Nothing becomes unzip since you don't have a variable called 'zip' so zip.extract() does nothing

0 Kudos
DanPatterson_Retired
MVP Emeritus

Research the module would help

import zipfile
zipfile.ZipFile('c:/source_folder/some.zip').extractall('c:/somefolder')
0 Kudos
Yaron_YosefCohen
Occasional Contributor II

thanks Dan for your helps.

this code works fine:

import logging,zipfile

from pathlib import Path

from shutil import unpack_archive

zip_files = Path(r"C:\Project\layers").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')