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

标签 python zip

我想将文件从 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'

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

最佳答案

它对您不起作用的原因是,当您尝试读取该文件时,该文件尚未关闭(写入磁盘)。

有两种方法可以解决此问题 - 一种是将最后一个 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)

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

关于python - 从 zip 复制文件并同时读取该文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355830/

相关文章:

Python编辑xml文件

Python:打开不带扩展名 ".zip"的zip文件

java - 如何压缩代码中生成的文件 (Java)

python - 需要指导将 python 脚本中的数据插入 MySQL 数据库

python - 基于正则表达式 python 规则的 eliza 实现

python - 功能建议中这些符号的含义是什么?

xml - 从解压缩的 xml 文件夹重新创建 excel .xlsx 文件

c# - 如何使用 C# 解压缩压缩文件?

ios - 如何在 iOS 上下载和解压缩文件

Python 和 Pandas 查询 API 和更新数据库