提取压缩文件

如何解决提取压缩文件

| 以下代码允许我提取.tgz文件。但是,它会在大约下降两级后停止提取。还有其他子文件夹具有.tgz文件,需要解压缩。此外,提取文件时,必须手动将其移至其他路径,否则它将被提取到该位置的其他.tgz文件覆盖(我使用的所有.tgz文件都具有相同的文件结构/文件夹名称一旦提取)。任何帮助表示赞赏。谢谢!
import os,sys,tarfile

def extract(tar_url,extract_path=\'.\'):
    print tar_url
    tar = tarfile.open(tar_url,\'r\')
    for item in tar:
        tar.extract(item,extract_path)
        if item.name.find(\".tgz\") != -1 or item.name.find(\".tar\") != -1:
            extract(item.name,\"./\" + item.name[:item.name.rfind(\'/\')])
try:

    extract(sys.argv[1] + \'.tgz\')
    print \'Done.\'
except:
    name = os.path.basename(sys.argv[0])
    print name[:name.rfind(\'.\')],\'<filename>\'
    

解决方法

如果我没有误解您的问题,那么这就是您想要做的- 提取可能包含以下内容的.tgz文件: 其中更多需要进一步的.tgz文件 提取(依此类推) 解压缩时,请注意不要替换文件夹中已经存在的目录。 如果我正确解释了您的问题,那么... 这是我的代码的作用- 将每个.tgz文件(递归)提取到与该目录中.tgz文件(没有扩展名)同名的单独文件夹中。 提取时,请确保它不会覆盖/替换任何现有的文件/文件夹。 因此,如果这是.tgz文件的目录结构-
parent/
    xyz.tgz/
        a
        b
        c
        d.tgz/
            x
            y
            z
        a.tgz/                  # note if I extract this directly,it will replace/overwrite contents of the folder \'a\'
            m
            n
            o
            p
解压缩后,目录结构将为-
parent/
    xyz.tgz
    xyz/
        a
        b
        c
        d/
            x
            y
            z
        a 1/                  # it extracts \'a.tgz\' to the folder \'a 1\' as folder \'a\' already exists in the same folder.
            m
            n
            o
            p
尽管我在下面的代码中提供了大量文档,但是我只是简要介绍了程序的结构。这是我定义的功能-
FileExtension --> returns the extension of a file
AppropriateFolderName --> helps in preventing overwriting/replacing of already existing folders (how? you will see it in the program)
Extract --> extracts a .tgz file (safely)
WalkTreeAndExtract - walks down a directory (passed as parameter) and extracts all .tgz files(recursively) on the way down.
我无法建议您对所做的操作进行更改,因为我的方法有些不同。我使用的是
tarfile
模块的
extractall
方法,而不是像您所做的那样有点复杂的
extract
方法。 (请看一下-http://docs.python.org/library/tarfile.html#tarfile.TarFile.extractall并阅读与使用
extractall
方法相关的警告。我认为我们不会遇到任何此类问题一般而言,但请记住这一点。) 所以这是对我有用的代码- (我尝试对嵌套5个深度的
.tar
文件(即
.tar
内的
.tar
中的
.tar
... 5次)进行了测试,但它适用于任何深度*,也适用于
.tgz
文件。)
# extracting_nested_tars.py

import os
import re
import tarfile

file_extensions = (\'tar\',\'tgz\')
# Edit this according to the archive types you want to extract. Keep in
# mind that these should be extractable by the tarfile module.

def FileExtension(file_name):
    \"\"\"Return the file extension of file

    \'file\' should be a string. It can be either the full path of
    the file or just its name (or any string as long it contains
    the file extension.)

    Examples:
    input (file) -->  \'abc.tar\'
    return value -->  \'tar\'

    \"\"\"
    match = re.compile(r\"^.*[.](?P<ext>\\w+)$\",re.VERBOSE|re.IGNORECASE).match(file_name)

    if match:           # if match != None:
        ext = match.group(\'ext\')
        return ext
    else:
        return \'\'       # there is no file extension to file_name

def AppropriateFolderName(folder_name,parent_fullpath):
    \"\"\"Return a folder name such that it can be safely created in
    parent_fullpath without replacing any existing folder in it.

    Check if a folder named folder_name exists in parent_fullpath. If no,return folder_name (without changing,because it can be safely created 
    without replacing any already existing folder). If yes,append an
    appropriate number to the folder_name such that this new folder_name
    can be safely created in the folder parent_fullpath.

    Examples:
    folder_name = \'untitled folder\'
    return value = \'untitled folder\' (if no such folder already exists
                                      in parent_fullpath.)

    folder_name = \'untitled folder\'
    return value = \'untitled folder 1\' (if a folder named \'untitled folder\'
                                        already exists but no folder named
                                        \'untitled folder 1\' exists in
                                        parent_fullpath.)

    folder_name = \'untitled folder\'
    return value = \'untitled folder 2\' (if folders named \'untitled folder\'
                                        and \'untitled folder 1\' both
                                        already exist but no folder named
                                        \'untitled folder 2\' exists in
                                        parent_fullpath.)

    \"\"\"
    if os.path.exists(os.path.join(parent_fullpath,folder_name)):
        match = re.compile(r\'^(?P<name>.*)[ ](?P<num>\\d+)$\').match(folder_name)
        if match:                           # if match != None:
            name = match.group(\'name\')
            number = match.group(\'num\')
            new_folder_name = \'%s %d\' %(name,int(number)+1)
            return AppropriateFolderName(new_folder_name,parent_fullpath)
            # Recursively call itself so that it can be check whether a
            # folder named new_folder_name already exists in parent_fullpath
            # or not.
        else:
            new_folder_name = \'%s 1\' %folder_name
            return AppropriateFolderName(new_folder_name,parent_fullpath)
            # Recursively call itself so that it can be check whether a
            # folder named new_folder_name already exists in parent_fullpath
            # or not.
    else:
        return folder_name

def Extract(tarfile_fullpath,delete_tar_file=True):
    \"\"\"Extract the tarfile_fullpath to an appropriate* folder of the same
    name as the tar file (without an extension) and return the path
    of this folder.

    If delete_tar_file is True,it will delete the tar file after
    its extraction; if False,it won`t. Default value is True as you
    would normally want to delete the (nested) tar files after
    extraction. Pass a False,if you don`t want to delete the
    tar file (after its extraction) you are passing.

    \"\"\"
    tarfile_name = os.path.basename(tarfile_fullpath)
    parent_dir = os.path.dirname(tarfile_fullpath)

    extract_folder_name = AppropriateFolderName(tarfile_name[:\\
    -1*len(FileExtension(tarfile_name))-1],parent_dir)
    # (the slicing is to remove the extension (.tar) from the file name.)
    # Get a folder name (from the function AppropriateFolderName)
    # in which the contents of the tar file can be extracted,# so that it doesn\'t replace an already existing folder.
    extract_folder_fullpath = os.path.join(parent_dir,extract_folder_name)
    # The full path to this new folder.

    try:
        tar = tarfile.open(tarfile_fullpath)
        tar.extractall(extract_folder_fullpath)
        tar.close()
        if delete_tar_file:
            os.remove(tarfile_fullpath)
        return extract_folder_name
    except Exception as e:
        # Exceptions can occur while opening a damaged tar file.
        print \'Error occured while extracting %s\\n\'\\
        \'Reason: %s\' %(tarfile_fullpath,e)
        return

def WalkTreeAndExtract(parent_dir):
    \"\"\"Recursively descend the directory tree rooted at parent_dir
    and extract each tar file on the way down (recursively).
    \"\"\"
    try:
        dir_contents = os.listdir(parent_dir)
    except OSError as e:
        # Exception can occur if trying to open some folder whose
        # permissions this program does not have.
        print \'Error occured. Could not open folder %s\\n\'\\
        \'Reason: %s\' %(parent_dir,e)
        return

    for content in dir_contents:
        content_fullpath = os.path.join(parent_dir,content)
        if os.path.isdir(content_fullpath):
            # If content is a folder,walk it down completely.
            WalkTreeAndExtract(content_fullpath)
        elif os.path.isfile(content_fullpath):
            # If content is a file,check if it is a tar file.
            # If so,extract its contents to a new folder.
            if FileExtension(content_fullpath) in file_extensions:
                extract_folder_name = Extract(content_fullpath)
                if extract_folder_name:     # if extract_folder_name != None:
                    dir_contents.append(extract_folder_name)
                    # Append the newly extracted folder to dir_contents
                    # so that it can be later searched for more tar files
                    # to extract.
        else:
            # Unknown file type.
            print \'Skipping %s. <Neither file nor folder>\' % content_fullpath

if __name__ == \'__main__\':
    tarfile_fullpath = \'fullpath_path_of_your_tarfile\'    # pass the path of your tar file here.
    extract_folder_name = Extract(tarfile_fullpath,False)

    # tarfile_fullpath is extracted to extract_folder_name. Now descend
    # down its directory structure and extract all other tar files
    # (recursively).
    extract_folder_fullpath = os.path.join(os.path.dirname(tarfile_fullpath),extract_folder_name)
    WalkTreeAndExtract(extract_folder_fullpath)
    # If you want to extract all tar files in a dir,just execute the above
    # line and nothing else.
我还没有添加命令行界面。我想如果您觉得有用的话,可以添加它。 这是上述程序的更好的版本- http://guanidene.blogspot.com/2011/06/nested-tar-archives-extractor.html     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-