【问题标题】:Extract the content of a specific folder from a zip archive in Python3从 Python3 中的 zip 存档中提取特定文件夹的内容
【发布时间】:2020-02-19 12:58:21
【问题描述】:

我有一个 zip 存档,其内部结构如下所示:

file.zip
  |
   --- foo/
  |
   --- bar/
        |
         --- file1.txt
        |
         --- dir/
              |
               --- file2.txt

我想使用 python3 将bar 的内容提取到输出目录,得到如下所示的内容:

output-dir/
    |
     --- file1.txt
    |
     --- dir/
          |
           --- file2.txt

但是,当我在bar 下面运行代码时,它的内容被提取到output-dir

import zipfile

archive = zipfile.ZipFile('path/to/file.zip')

for archive_item in archive.namelist():
    if archive_item.startswith('bar/'):
        archive.extract(archive_item, 'path/to/output-dir')

我该如何解决这个问题? 谢谢!

【问题讨论】:

  • 不是真正的解决方案,而是一种规避问题的方法:解压到path/to,得到path/to/bar,然后将path/to/bar 重命名为path/to/output-dir。
  • 更改archive_item.startswith('file/bar/')会给出bar目录内容

标签: python python-3.x zipfile


【解决方案1】:

不要使用ZipFile.extract,而是使用ZipFile.open、open 和shutil.copyfileobj 以便将文件准确地放在您想要的位置,使用路径操作来创建输出你需要的路径。

archive = zipfile.ZipFile('path/to/file.zip')
PREFIX = 'bar/'
out = pathlib.Path('path/to/output-dir')
for archive_item in archive.namelist():
    if archive_item.startswith(PREFIX):
        # strip out the leading prefix then join to `out`, note that you 
        # may want to add some securing against path traversal if the zip
        # file comes from an untrusted source
        destpath = out.joinpath(archive_item[len(PREFIX):])
        # make sure destination directory exists otherwise `open` will fail
        os.makedirs(destpath.parent, exist_ok=True)
        with archive.open(archive_item) as source,
             open(destpath, 'wb') as dest:
            shutil.copyfileobj(source, dest)

类似的东西。

【讨论】:

  • 我建议把4改成len('bar/'),这样更容易修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多