从Python3中的zip存档中提取特定文件夹的内容

输入错误

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

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

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

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')

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

马斯林

要使用路径操纵来创建所需的输出路径,请不要使用ZipFile.extract和使用来将文件准确地放置在所需位置ZipFile.open而是使用openshutil.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)

这样的事情。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从压缩的存档中仅提取特定文件夹的内容到给定目录

从子文件夹中的 zip 文件中提取文件

将文件夹内容从7z存档提取到特定文件夹

从Zip中提取特定的子文件夹

将ZIP存档中的文件夹内的文件提取到当前文件夹

如何从S3中的zip存档中提取文件

7z的命令行从存档内的特定文件夹中提取特定文件

7-Zip命令行从存档中提取文件夹

如何从特定文件夹中提取文件,文件名存储在python列表中?

如何从python中的.tar存档中提取特定文件?

从 (GNU)tar 存档中提取子文件夹

如果存档中没有子文件夹,如何在RAR / ZIP提取中创建子文件夹?

给定 Colab 中的文件夹路径,如何在 python 中提取其中的特定部分?

7z-我可以从控制台中提取存档中仅一个文件夹的内容吗?

提取文件夹中的Zip文件

如何使用SharpZipLib从zip文件中提取文件夹?

如何从MATLAB中的zip存档中提取单个文件?

是否有一个powershell脚本可以从文件夹A中提取按日期排序的前3个zip文件夹并将它们提取到文件夹B中?

ExtractToDirectory ,如何使用 c# 在 zip 文件夹中提取 zip 文件夹

使用密码从ZIP存档中提取文件

从zip存档中提取gzip文件

Python:无法从tar中仅提取特定文件夹

如何在Linux中将多个7zip存档提取到具有相同名称的文件夹中?

从 zip 存档中提取文件是否比从同一存档中复制文件更快?

如何从 Windows 中的文件夹中提取特定的文件列表?

如何从Python3中的json文件中提取协调

如何使从存档中提取的文件继承父文件夹的权限

通过Powershell从zip提取特定文件似乎不希望在子文件夹中查找

从tar.gz中提取特定文件夹