简体   繁体   中英

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM