Reputation: 127
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?
Upvotes: 3
Views: 7390
Reputation: 127
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)
Upvotes: 5
Reputation: 174
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)
Upvotes: 2
Reputation: 1529
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()
Upvotes: -2