从 tar 中只提取一个目录 [英] Extract only a single directory from tar

查看:59
本文介绍了从 tar 中只提取一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 python 处理一个项目,在该项目中我只需要提取 tar 存档的一个子文件夹,而不是所有文件.我尝试使用

I am working on a project in python in which I need to extract only a subfolder of tar archive not all the files. I tried to use

tar = tarfile.open(tarfile)
tar.extract("dirname", targetdir)

但这不起作用,它不会提取给定的子目录,也不会引发异常.我是python的初学者.此外,如果上述功能不适用于目录,此命令和 tar.extractfile() 之间有什么区别?

But this does not work, it does not extract the given subdirectory also no exception is thrown. I am a beginner in python. Also if the above function doesn't work for directories whats the difference between this command and tar.extractfile() ?

推荐答案

tarfile 模块文档,您可以使用以下内容提取包含的子文件夹及其所有内容:

Building on the second example from the tarfile module documentation, you could extract the contained sub-folder and all of its contents with something like this:

with tarfile.open("sample.tar") as tar:
    subdir_and_files = [
        tarinfo for tarinfo in tar.getmembers()
        if tarinfo.name.startswith("subfolder/")
    ]
    tar.extractall(members=subdir_and_files)

这会创建子文件夹及其内容的列表,然后使用推荐的 extractall() 方法来提取它们.当然,将 "subfolder/" 替换为您要提取的子文件夹的实际路径(相对于 tar 文件的根目录).

This creates a list of the subfolder and its contents, and then uses the recommended extractall() method to extract just them. Of course, replace "subfolder/" with the actual path (relative to the root of the tar file) of the sub-folder you want to extract.

这篇关于从 tar 中只提取一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆