Python zipfile 从 zip 文件中的目录中提取文件

Python zipfile extract files from directory inside a zip file

我需要将一些文件解压缩到 zip 文件中的目录中。

主要问题是我只想从此目录中提取内容,而不是包含所有文件的目录本身。

我试过使用 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)