提取给定目录中具有目录路径的所有文件
我有一个tar存档,其中有一个目录,需要在给定目录中提取该目录. 例如:我有一个目录
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
TarPrefix/x/y/z
在tar归档文件中,我想将其提取到给定的目标目录中,例如:extracted/a/此目录应包含目录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/")
]
获取目录路径"subfolder/"中所有成员的列表,然后使用tar.extractall(extracted/a,subdir_and_files)
提取它
但是它将提取所有成员及其目录路径.例如,这将导致extract/a/x/y/z.
您能帮我提取给定文件夹中的这些文件吗?
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.
看起来您可能已经找到了答案,但是无论如何这是我的版本:
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]))