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

后端 未结 5 1656
栀梦
栀梦 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:24

    It is possible to iterate over the ZipFile.infolist(). On the returned ZipInfo objects you can then manipulate the filename to remove the directory part and finally extract it to a specified directory.

    import glob
    import zipfile
    import shutil
    import os
    
    my_dir = "D:\\Download\\"
    my_zip = "D:\\Download\\my_file.zip"
    
    with zipfile.ZipFile(my_zip) as zip:
        for zip_info in zip.infolist():
            if zip_info.filename[-1] == '/':
                continue
            zip_info.filename = os.path.basename(zip_info.filename)
            zip.extract(zip_info, my_dir)
    

提交回复
热议问题