kishore
kishore

Reputation: 127

copy file from zip and read that file same time

I want to copy a file from Zip file to separate folder and read that file at same time. The file is copied to specific folder if I comment that last two lines.

The code I tried is:

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)
        with open('AccountService.json') as json_data:
            j=json.load(json_data)

But it gave following error:

Traceback (most recent call last):
File "schema.py", line 21, in <module>
with open('AccountService.json') as json_data:
IOError: [Errno 2] No such file or directory: 'AccountService.json'

My question is it possible to copy that file and read contents of that file same time?

Upvotes: 1

Views: 107

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174700

The reason its not working for you is because the file is not yet closed (written to disk) when you try to read it.

Two ways you can fix this - one is simply by moving the final with statement outside of the first with statement:

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)
with open('AccountService.json') as json_data:
    j=json.load(json_data)

This way, your file should be written and available to you.

However, a simpler way is to just read the contents of the zip file, before you copy it:

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:
        j = json.load(zf) # read the contents here.
        shutil.copyfileobj(zf, f) # copy the file

        #with open('AccountService.json') as json_data:
        #    j=json.load(json_data)

Now, you don't need to open the other file anymore.

Upvotes: 1

Related Questions