Extract all files with a directory in a given directory

I have a tar archive in which I have a directory that I need to extract in this directory. For example: I have a directory

TarPrefix / x / y / g

in the tar archive I want to extract it to this target directory, for example: extract / a / this directory should contain all the files and directories contained in the TarPrefix / x / y / z directory.

subdir_and_files = [ tarinfo for tarinfo in tar.getmembers() if tarinfo.name.startswith("subfolder/") ] 

to get a list of all the members in the path of the "Subfolder /" directory, and then I extract it with tar.extractall(extracted/a,subdir_and_files) but it extracts all the members with their directory path. For example, this results in the extraction of / a / x / y / z. Could you help me in extracting these files in this folder.

+7
source share
2 answers

It sounds like you already found the answer, but here is my version:

 import sys, tarfile def get_members(tar, prefix): if not prefix.endswith('/'): prefix += '/' offset = len(prefix) for tarinfo in tar.getmembers(): if tarinfo.name.startswith(prefix): tarinfo.name = tarinfo.name[offset:] yield tarinfo args = sys.argv[1:] if len(args) > 1: tar = tarfile.open(args[0]) path = args[2] if len(args) > 2 else '.' tar.extractall(path, get_members(tar, args[1])) 
+12
source
 with tarfile.open('sourcefile.tgz', 'r:gz') as _tar: for member in _tar: if member.isdir(): continue fname = member.name.rsplit('/',1)[1] _tar.makefile(member, 'desination_dir' + '/' + fname) 
+2
source

All Articles