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

后端 未结 5 1652
栀梦
栀梦 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条回答
  •  萌比男神i
    2020-11-27 16:26

    Just extract to bytes in memory,compute the filename, and write it there yourself, instead of letting the library do it - -mostly, just use the "read()" instead of "extract()" method:

    Python 3.6+ update(2020) - the same code from the original answer, but using pathlib.Path, which ease file-path manipulation and other operations (like "write_bytes")

    from pathlib import Path
    import zipfile
    import os
    
    my_dir = Path("D:\\Download\\")
    my_zip = my_dir / "my_file.zip"
    
    zip_file = zipfile.ZipFile(my_zip, 'r')
    for files in zip_file.namelist():
        data = zip_file.read(files, my_dir)
        myfile_path = my_dir / Path(files.filename).name
        myfile_path.write_bytes(data)
    zip_file.close()
    

    Original code in answer without pathlib:

    import zipfile
    import os
    
    my_dir = "D:\\Download\\"
    my_zip = "D:\\Download\\my_file.zip"
    
    zip_file = zipfile.ZipFile(my_zip, 'r')
    for files in zip_file.namelist():
        data = zip_file.read(files, my_dir)
        # I am almost shure zip represents directory separator
        # char as "/" regardless of OS, but I  don't have DOS or Windos here to test it
        myfile_path = os.path.join(my_dir, files.split("/")[-1])
        myfile = open(myfile_path, "wb")
        myfile.write(data)
        myfile.close()
    zip_file.close()
    

提交回复
热议问题