我有几个tar文件,目录结构如下:a/b/c/xyz.txt
我想通过忽略父目录'a'来从这些tar文件中提取文件。在提取之后,我期望得到以下目录结构:b/c/xyz.txt
对于tar命令,我们可以使用--strip=1选项。
现在,在Equivalent functionality of tar --strip in python tarfile中,对于一个具有明确名称的目录'a'的tar文件,已经要求这样做,但是我有一个额外的问题。
tarfile 'A'的目录'a'名为'projectname-1d30420',tarfile 'B'的目录名为'differentprojectname-ed1d5db','C'的目录名为'Z',依此类推。
如何在python中使用tarfile实现这一点?
发布于 2021-04-29 17:04:04
如果您有路径a/b/c,那么您可以在第一个/上拆分它,并获取最后一个元素来获取b/c
path = path.split('/', 1)[-1]您甚至可以使用变量来获得与--strip相同的结果
strip = 1 # 2, 3, etc.
path = path.split('/', strip)[-1]基于你的链接中的代码,但我没有测试它
def members(tar, strip):
for member in tar.getmembers():
member.path = member.path.strip('/', strip)[-1]
yield member
# --- main ---
strip = 1
with tarfile.open("sample.tar") as tar:
tar.extractall(members=members(tar, strip))https://stackoverflow.com/questions/67312764
复制相似问题