简体   繁体   English

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

[英]Python zipfile extract files from directory inside a zip file

I need to extract some files inside a directory in a zip file.我需要在一个 zip 文件的目录中提取一些文件。

The main problem is that I want to extract only the contents from this directory, not the directory itself with all the files inside.主要问题是我只想从这个目录中提取内容,而不是包含所有文件的目录本身。

I've tried by iterating on them using namelist() or tweaking it with zipfile.Path() , unsuccessfully.我尝试使用namelist()迭代它们或使用zipfile.Path()对其进行调整, zipfile.Path()成功。

This works but it extracts the directory with the files (like extractall() does).这有效,但它会提取包含文件的目录(如extractall()那样)。 Path doesn't work because raises KeyError saying that the item doesn't exist yet it does. Path 不起作用,因为引发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)

written from my mobile but I expect it to work:用我的手机写的,但我希望它能正常工作:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM