简体   繁体   中英

extract certain file from zip but not complete directory

I have implemented the following code to copy a specific file from zip to a certain target directory.

But this copies entire structure into the target directory. The code is:

import os
import zipfile 

zip_filepath='/home/sundeep/Desktop/SCHEMA AUTOMATION/SOURCE/DSP8010_2017.1.zip'
target_dir='/home/sundeep/Desktop/SCHEMA AUTOMATION/SCHEMA'

with zipfile.ZipFile(zip_filepath) as zf:
    dirname = target_dir
    zf.extract('DSP8010_2017.1/json-schema/AccountService.json',path=dirname)

My question is how can I copy only AccountService.json file to target directory but not the entire structure. Any possibility by implementing shutil?

You can add file name into existing directory like this:-

a = 'DSP8010_2017.1/json-schema/AccountService.json'
dirname = target_dir+"/"+(a.split('/')[-1])

As you said having issue you can try like this:-

import zipfile

zip_filepath='/home/sundeep/Desktop/SCHEMA AUTOMATION/SOURCE/DSP8010_2017.1.zip'
target_dir='/home/sundeep/Desktop/SCHEMA AUTOMATION/SCHEMA'

fantasy_zip = zipfile.ZipFile(zip_filepath)
file = fantasy_zip.extract('AccountService.json', zip_filepath)
target_dir = target_dir+"/"+file 
fantasy_zip.close()

Try this:-

import zipfile


zip_filepath='/home/sundeep/Desktop/SCHEMA AUTOMATION/SOURCE/DSP8010_2017.1.zip'

target_dir='/home/sundeep/Desktop/SCHEMA AUTOMATION/SCHEMA'


with zipfile.ZipFile(zip_filepath) as zf:

       for file in zf.namelist():

            if file.endswith("AccountService.json"):
                zf.extract(file,target_dir)
import os
import shutil
import zipfile

zip_filepath='/home/sundeep/Desktop/SCHEMA AUTOMATION/SOURCE/DSP8010_2017.1.zip'
target_dir='/home/sundeep/Desktop/SCHEMA AUTOMATION/SCHEMA'


with zipfile.ZipFile(zip_filepath) as z:
    with z.open('DSP8010_2017.1/json-schema/AccountService.json') as zf, open(os.path.join(target_dir, os.path.basename('AccountService.json')), 'wb') as f:
        shutil.copyfileobj(zf, f) 

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