【问题标题】:Python; how to extract files without including parent directoryPython;如何在不包含父目录的情况下提取文件
【发布时间】:2020-05-21 05:53:31
【问题描述】:

我是 Python 的菜鸟,我需要帮助!我正在尝试将 zipfile 模块用于最新版本的 Python 3,并且在准备提取 zip 文件时尝试排除父目录(文件夹)时遇到了麻烦。

zip 文件目录的示例如下所示:

Content/
Content/Runtime/
Content/Runtime/test.txt
Content/Runtime/test.png
Content/Documentation/
Content/Documentation/license.txt

我不知道如何从提取中排除父目录(第一个文件夹)。我只想提取运行时和文档目录及其内容。

请帮忙,谢谢,非常感谢!

【问题讨论】:

    标签: python unix extract zipfile


    【解决方案1】:

    在这种情况下,用于提取的内置方法将不起作用(因为它们会提取完整路径),但您可以自己轻松完成:

    import os
    import shutil
    
    destination_dir = './destination'
    
    with zipfile.ZipFile('./tmp.zip', 'r') as z:
        # See https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.infolist
        for file_info in z.infolist():
            # Only extract regular files
            if file_info.is_dir():
                continue
    
            file_path = file_info.filename
            # Only extract things under 'Content/'
            if not file_path.startswith('Content/'):
                continue
    
            # Split at slashes, at most one time, and take the second part
            # so that we skip the 'Content/' part
            extracted_path = file_path.split('/', 1)[1]
    
            # Combine with the destination directory
            extracted_path = os.path.join(destination_dir, extracted_path)
            print(extracted_path)
    
            # Make sure the directory for the file exists
            os.makedirs(os.path.dirname(extracted_path), exist_ok=True)
    
            # Extract the file. Don't use `z.extract` as it will concatenate
            # the full path from inside the zip.
            # WARNING: This code does not check for path traversal vulnerabilities
            # Refer to the big warning inside the ZipFile module for more details
            with open(extracted_path, 'wb') as dst:
              with z.open(file_info, 'r') as src:
                shutil.copyfileobj(src, dst)
    

    【讨论】:

    • 您好,我使用了您提供的代码,并且看起来,z.extract(file_info, extracted_path) 仍在使用父目录进行提取。此外,os.makedirs 正在为非目录/文件创建文件夹名称。
    • @dadinsafeland 我在手机上写了代码,所以之前没有调试过?现在修复并检查
    • 哇哦!有效。起初,由于目录已经存在,我遇到了权限被拒绝错误,但这是一个快速修复。非常感谢你,你是一个救生员!
    猜你喜欢
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多