问题描述
主要问题是我只想提取该目录中的内容,而不提取其中包含所有文件的目录本身。
我尝试使用namelist()
对其进行迭代,或者使用zipfile.Path()
对其进行调整,但均未成功。
这可行,但它会提取包含文件的目录(就像extractall()
一样)。路径无效,因为引发KeyError
表示该项目尚不存在。
for zip_file in zip_files:
with zipfile.ZipFile(os.path.join(home_path,zip_file),'r') as zip_ref:
files = [n for n in zip_ref.namelist()]
zip_ref.extractall(os.path.join(home_path,'dir'),members=files)
解决方法
是用我的手机写的,但我希望它能正常工作
from pathlib import Path
with ZipFile(zipfile_path,"r") as zf:
for f in zf.namelist():
if f.startswith('/'):
continue
source = zf.open(f)
target = open(target_dir / Path(f).name,"wb")
with source,target:
shutil.copyfileobj(source,target)