Extract all files with directory path in given directory

核能气质少年 提交于 2019-12-05 23:13:30

问题


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 it in a given target directory for example: extracted/a/ this directory should contain all the files and directories contained in directory TarPrefix/x/y/z.

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

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


回答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]))



回答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)


来源:https://stackoverflow.com/questions/8259769/extract-all-files-with-directory-path-in-given-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!