Unzip zip files in folders and subfolders with python

北战南征 提交于 2019-11-27 16:57:49

问题


I try to unzip 150 zip files. 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 . my code is:

import zipfile    
import os,os.path,sys  

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.


回答1:


UPDATE:

Finally, this code worked for me:

import zipfile,fnmatch,os

rootPath = r"C:\Project"
pattern = '*.zip'
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        print(os.path.join(root, filename))
        zipfile.ZipFile(os.path.join(root, filename)).extractall(os.path.join(root, os.path.splitext(filename)[0]))



回答2:


You could use Path.rglob() to enumerate zip-files recursively and shutil.unpack_archive() to unpack zip files:

#!/usr/bin/env python3
import logging
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')

It "extract[s] 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" e.g., it extracts 'layers/dir/file.zip' archive into 'layers/dir/file' directory.




回答3:


To unzip all the files into a temporary folder (Ubuntu)

import tempfile
import zipfile

tmpdirname = tempfile.mkdtemp()

zf = zipfile.ZipFile('/path/to/zipfile.zip')

for fn in zf.namelist():
    temp_file = tmpdirname+"/"+fn
    #print(temp_file)

    f = open(temp_file, 'w')
    f.write(zf.read(fn).decode('utf-8'))
    f.close()


来源:https://stackoverflow.com/questions/28339000/unzip-zip-files-in-folders-and-subfolders-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!