Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 553
kishore Avatar asked Dec 14 '25 17:12

kishore


1 Answers

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) 
like image 200
kishore Avatar answered Dec 16 '25 19:12

kishore