Extracting file from tarfile with only basename us

2019-07-31 09:59发布

I have a 'tafile' which contains files with complete path '/home/usr/path/to/file'. When I extract the file to the curent folder it creates the complete path recursively. Is there a way that I can extract the file with only the base name.

3条回答
欢心
2楼-- · 2019-07-31 10:04

Use TarFile.extractfile() and write it into a file of your choice.

查看更多
时光不老,我们不散
3楼-- · 2019-07-31 10:15

You can change the arcnames by hacking the TarInfo objects you get from Tarfile.getmembers(). Then you can use Tarfile.extractall to write the members to your chosen destination under their new names.

E.g., the following function will select members from an arbitrary subtree of the archive and extract them to a destination under their base names:

def extractTo(tar, dest, selector):
    if type(selector) is str:
        prefix = selector
        selector = lambda m: m.name.startswith(prefix)
    members = [m for m in tar.getmembers() if selector(m)]
    for m in members:
        m.name = os.path.basename(m.name)
    tar.extractall(path = dest, members = members)

Suppose tar is a TarFile instance representing an archive with some members in a utilities/misc directory, and you would like to fold those members into the local/bin directory. You could do:

extractTo(tar, 'local/bin', 'utilities/misc/')

Note the trailing / on the directory prefix. We don't want to add the misc directory to `local/bin', rather, just its members.

查看更多
孤傲高冷的网名
4楼-- · 2019-07-31 10:19

You can use the functionextractall to fit your needs. According to the documentation : Extract all members from the archive to the current working directory or directory path.

TarFile.extractall(path="my/path")
查看更多
登录 后发表回答