Extract files from zip without keeping the structure using python ZipFile?

后端 未结 5 1657
栀梦
栀梦 2020-11-27 16:10

I try to extract all files from .zip containing subfolders in one folder. I want all the files from subfolders extract in only one folder without keeping the original struc

5条回答
  •  甜味超标
    2020-11-27 16:41

    This opens file handles of members of the zip archive, extracts the filename and copies it to a target file (that's how ZipFile.extract works, without taken care of subdirectories).

    import os
    import shutil
    import zipfile
    
    my_dir = r"D:\Download"
    my_zip = r"D:\Download\my_file.zip"
    
    with zipfile.ZipFile(my_zip) as zip_file:
        for member in zip_file.namelist():
            filename = os.path.basename(member)
            # skip directories
            if not filename:
                continue
    
            # copy file (taken from zipfile's extract)
            source = zip_file.open(member)
            target = open(os.path.join(my_dir, filename), "wb")
            with source, target:
                shutil.copyfileobj(source, target)
    

提交回复
热议问题