Python: renaming an element in tar file during extraction

Premise

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

Problem

Extract baz contents to archive on /foo/bar

Example

The archive contains:

  baz /
  file1.txt

The source directory contains:

  foo /
   bar /
     file2.txt

After extracting, 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 destination location, this works because the baz directory will always have the same name.

Any other ideas?

+4
source share
1 answer

You can use the tarfile libraries extract() , extractall() or extractfile() . Therefore, you must have access to non-top-level objects in the archive.

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

You will probably have the first call to getmembers() , then drag the list down so you want, then call one of the above extraction methods.

+2
source

Source: https://habr.com/ru/post/1379908/


All Articles