2

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 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is a solution but I would rather like to rename the file instead of copying each line.
You can't help but "copy each line", as that's how extracting is done. shutil.copyfileobj is a convenient tool to do the copying yourself.
4

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.

Comments

0

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

3 Comments

The 'tarfile' is not being created by me. Is there a way I can change the arcname after the tarfile is created?
Yes, sorry, that's what I became aware after a more careful reading ! Please see my edit, it should fit your needs better.
It still creates the folders recursively, as in 'my/path//home/usr/path/to/file'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.