Python:我如何访问tarfile.add文件add()的筛选器方法中的()的'name'参数?

2024-09-26 22:10:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在使用tarfile(python3.4)创建tar(gz)文件时过滤子目录(跳过它们)。你知道吗

磁盘上的文件:

  • /主页/myuser/temp/test1/
  • /主页/myuser/temp/test1/home/foo.txt文件你知道吗
  • /主页/myuser/temp/test1/thing/酒吧.jpg你知道吗
  • /主页/myuser/temp/test1/lemon/果汁.png你知道吗
  • /主页/myuser/temp/test1/

试图用tarfile.add()压缩/home/myuser/temp/test1/。你知道吗

我使用带路径模式和不带路径模式。完整路径可以,但短路径有一个问题: 目录排除不起作用,因为tarfile.add文件()将arcname参数传递给filter method-notname参数!

archive.add(entry, arcname=os.path.basename(entry), filter=self.filter_general)

示例:

文件:/home/myuser/temp/test1/thing/bar.jpg->;arcname = test1/thing/bar.jpg

因此,由于exclude_dir_fullpath中的/home/myuser/temp/test1/thing元素,filter方法应该排除此文件,但不能排除,因为filter方法得到test1/thing/bar.jpg。你知道吗

我如何访问tarfile.add文件()的“name”参数在筛选器方法中?

def filter_general(item):
    exclude_dir_fullpath = ['/home/myuser/temp/test1/thing', '/home/myuser/temp/test1/lemon']
    if any(dirname in item.name for dirname in exclude_dir_fullpath):
        print("Exclude fullpath dir matched at: %s" % item.name)  # DEBUG
        return None
    return item


def compress_tar():
    filepath = '/tmp/test.tar.gz'
    include_dir = '/home/myuser/temp/test1/'
    archive = tarfile.open(name=filepath, mode="w:gz")
    archive.add(include_dir, arcname=os.path.basename(include_dir), filter=filter_general)

compress_tar()

Tags: 文件路径addhomedir主页tarfilter
1条回答
网友
1楼 · 发布于 2024-09-26 22:10:55

您希望创建一个通用/可重用函数,以过滤给定绝对路径名的文件。我理解,仅对存档名称进行过滤是不够的,因为有时可以包含文件,也可以不包含文件,这取决于文件的来源。你知道吗

首先,在filter函数中添加一个参数

def filter_general(item,root_dir):
    full_path = os.path.join(root_dir,item.name)

然后,将“添加到存档”代码行替换为:

archive.add(include_dir, arcname=os.path.basename(include_dir), filter=lambda x: filter_general(x,os.path.dirname(include_dir)))

filter函数已被一个lambda替换,该函数传递include目录的目录名(否则,将重复根目录)

现在您的filter函数知道根目录,您可以按绝对路径进行过滤,从而允许您在代码中的多个位置重用filter函数。你知道吗

相关问题 更多 >

    热门问题