Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Renaming member in a tar file during extraction

Tags:

python

tarfile

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?

like image 237
Nicklas A. Avatar asked Oct 24 '22 19:10

Nicklas A.


1 Answers

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.

like image 99
jedwards Avatar answered Oct 27 '22 10:10

jedwards