Skip to content Skip to sidebar Skip to footer

Extracting File From Tarfile With Only Basename Using Python

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

Solution 1:

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.


Solution 2:


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

Post a Comment for "Extracting File From Tarfile With Only Basename Using Python"