gpt4 book ai didi

python - 从 zip 中提取某些文件但不是完整的目录

转载 作者:行者123 更新时间:2023-12-02 20:29:00 25 4
gpt4 key购买 nike

我已经实现了以下代码来将特定文件从 zip 复制到某个目标目录。

但这会将整个结构复制到目标目录中。代码是:

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)

我的问题是如何只将 AccountService.json 文件复制到目标目录而不是整个结构。实现 shutil 是否有可能?

最佳答案

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)

关于python - 从 zip 中提取某些文件但不是完整的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49313973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com