Extracting file from tarfile with only basename us

2019-07-31 10:19发布

问题:

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.

回答1:

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



回答2:

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.



回答3:

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