从zip复制文件并同时读取该文件

时间:2018-03-19 04:32:12

标签: python zipfile

我想将Zip文件中的文件复制到单独的文件夹并同时读取该文件。如果我评论最后两行,该文件将被复制到特定文件夹。

我尝试的代码是:

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)

但它出现了以下错误:

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'

我的问题是可以同时复制该文件并读取该文件的内容吗?

1 个答案:

答案 0 :(得分:1)

它不适合您的原因是因为当您尝试读取文件时文件尚未关闭(写入磁盘)。

您可以通过两种方式解决此问题 - 一种方法是将最终的with语句移到第一个with语句之外:

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)

这样,您的文件编写并可供您使用。

但是,更简单的方法是在复制之前只读取zip文件的内容:

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)

现在,您不再需要打开其他文件了。