Extract All Files With Directory Path In Given Directory
I have a tar archive in which I have a directory which I need to extract in a given directory. For example: I have a directory TarPrefix/x/y/z in a tar archive I want to extract
Solution 1:
Looks like you may have already found an answer, but here's my version anyway:
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]))
Solution 2:
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)
Post a Comment for "Extract All Files With Directory Path In Given Directory"