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

Python 从zip中提取某些文件,但不是完整的目录,python,zipfile,directory-structure,shutil,Python,Zipfile,Directory Structure,Shutil,我实现了以下代码,将特定文件从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_file

我实现了以下代码,将特定文件从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?

将文件名添加到现有目录中,如下所示:-

a = 'DSP8010_2017.1/json-schema/AccountService.json'
dirname = target_dir+"/"+(a.split('/')[-1])
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()
正如您所说,您可以这样尝试:-

a = 'DSP8010_2017.1/json-schema/AccountService.json'
dirname = target_dir+"/"+(a.split('/')[-1])
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()
试试这个:-

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)

@鲁尚45问题完全不同。此时将创建一个新文件夹。但y的要求是将特定文件复制到现有目录。抱歉,此代码正在创建名为“SCHEMAAccountService.json”的新目录,并再次像以前一样复制整个目录。@kishore edited try now您必须像这样将目录引用为“/”…抱歉,现在仍然很复杂。它将创建AccountService.json文件夹并复制整个目录,与该目录中的上一个目录相同。谢谢。。。但它仍在复制整个目录。现在,请检查您最新编辑的代码,我给出的代码正在生成相同的输出。他们正在将整个目录复制到目标文件夹。相反,我只需要将AccountService.json文件复制到目标文件夹中。这在逻辑上是不正确的,因为AccountService.json位于“DSP8010_2017.1/json schema/AccountService.json”目录中。在zf上使用名称列表操作是无效的。