Martan
Martan

Reputation: 605

Extract same file (name) from multiple Zips and store it as Zip Name = File Name (Python)

Have 1000+ zip files in a folder. All zips have same structure. Objective is to grab A.zip/folder/meta.xls from all zips and store it as A.xls, B.xls, C.xls..... etc.

I am new to python so I tried to construct below mentioned code. However it just create meta/file/meta.xls.

from zipfile import ZipFile
import os
files = os.listdir()
for file in files:
    with ZipFile(file,'r') as zip:
        zip.extract('meta/meta.xls','meta/file')

I think I am faulting in 'zip.extract('meta/meta.xls','meta/file') since the only meta.xls i get is the last item on list 'files'

Upvotes: 0

Views: 77

Answers (1)

Valentino
Valentino

Reputation: 7361

Your code is just overwriting the file because they have the same name. You need to rename each file.

from zipfile import ZipFile
import os
files = os.listdir()
for file in files:
    with ZipFile(file,'r') as zip:
        zip.extract('meta/meta.xls','meta/file')
        os.rename('meta/file/meta.xls', file.split('.')[0] + '.xls')

You should have now a lot of different xls files, each one named as the zip files from which is exctracted.

Upvotes: 1

Related Questions