我已经实现了以下代码,将特定文件从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的任何可能性?
答案 0 :(得分:0)
您可以将文件名添加到现有目录中,如下所示: -
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()
答案 1 :(得分:0)
试试这个: -
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)
答案 2 :(得分:0)
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)