I am working on a project in python in which I need to extract only a subfolder of tar archive not all the files. I tried to use
tar = tarfile.open(tarfile)
tar.extract("dirname", targetdir)
But this does not work, it does not extract the given subdirectory also no exception is thrown. I am a beginner in python. Also if the above function doesn't work for directories whats the difference between this command and tar.extractfile() ?
The other answer will retain the subfolder path, meaning that
subfolder/a/b
will be extracted to./subfolder/a/b
. To extract a subfolder to the root, sosubfolder/a/b
would be extracted to./a/b
, you can rewrite the paths with something like this:Building on the second example from the tarfile module documentation, you could extract the contained sub-folder and all of its contents with something like this:
This creates a list of the subfolder and its contents, and then uses the recommended
extractall()
method to extract just them. Of course, replace"subfolder/"
with the actual path (relative to the root of the tar file) of the sub-folder you want to extract.