Question

Premise

  • I have a directory /foo/bar
  • I have a tar file containing the directory baz

Problem

Extracting the contents of baz in the archive to /foo/bar

Example

The archive contains:

baz/
 file1.txt

The source directory contains:

foo/
  bar/
    file2.txt

After extraction I want it to be:

foo/
  bar/
    file1.txt
    file2.txt

Solutions so far

Extract to a temporary directory and then move the contents of baz to the target location, this works since I the baz directory will always have the same name.

Any other ideas?

Was it helpful?

Solution

You could use the tarfile library's extract(), extractall() or extractfile() methods. You should be able to access non-top-level objects in the archive this way.

Just note that the path in extractall() is not the path inside the archive, but rather the path you want to extract it to, so putting baz there will not help.

You'll probably have first call getmembers() then pare the list down to what you want, then call one of the above extract methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top