Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract files from a zip folder with sub folders into a single folder

Tags:

python

file

I have a zip folder with several subfolders. testfolder.zip contains files in the given format

testfolder/files 1,2,3
testfolder/Test1folder/files 5,6
testfolder/Test2folder/files 7,8

I need the output as

testfolder/files 1,2,3,4,5,6,7,8

I am able to unzip the folder with its subfolders but not in the desired way.

This is my attempt so far

import glob
import os
import zipfile
folder = 'E:/Test'
extension = '.zip'
zip_files = glob.glob(folder + extension)
for zip_filename in zip_files:
    dir_name = os.path.splitext(zip_filename)[0]
    os.mkdir(dir_name)
    zip_handler = zipfile.ZipFile(zip_filename, "r")
    zip_handler.extractall(dir_name)

Any help will be very appreciated.Thanks in advance.

like image 896
Anila A Avatar asked Nov 26 '25 08:11

Anila A


1 Answers

Replace:

zip_handler.extractall(dir_name)

with something like this:

for z in zip_handler.infolist():
    zip_handler.extract(z, dir_name)

This should by taking each file in the archive at a time and extracting it to the same point in the directory.

UPDATE: Apparently it still extracts them relatively. Solved it by adding a few lines of code to your original snippet:

for p, d, f in os.walk(folder, topdown= False):
for n in f:
    os.rename(os.path.join(p, n), os.path.join(dir_name, n))
for n in d:
    os.rmdir(os.path.join(p, n))    

This will move the files into the base folder and delete all empty folders that remain. This one I have tried and tested.

like image 185
Swakeert Jain Avatar answered Nov 28 '25 21:11

Swakeert Jain