【问题标题】:Python: how could I access tarfile.add()'s 'name' parameter in add()'s filter method?Python:如何在 add() 的过滤方法中访问 tarfile.add() 的 'name' 参数?
【发布时间】:2016-09-11 16:39:02
【问题描述】:

我想在使用 tarfile (python 3.4) 创建 tar(gz) 文件时过滤子目录(跳过它们)。

磁盘上的文件:

  • /home/myuser/temp/test1/
  • /home/myuser/temp/test1/home/foo.txt
  • /home/myuser/temp/test1/thing/bar.jpg
  • /home/myuser/temp/test1/lemon/juice.png
  • /home/myuser/temp/test1/

尝试将/home/myuser/temp/test1/ 压缩为tarfile.add()

我使用有路径和无路径模式。使用完整路径没关系,但使用短路径我有这个问题: 目录排除不起作用,因为 tarfile.add() 将 arcname 参数传递给过滤方法 - 而不是 name 参数!

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元素,过滤方法应该排除这个文件,但不能因为过滤方法得到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()

【问题讨论】:

  • 代码很复杂但不是独立的,因为有一些...。你能提供一个minimal reproducible example
  • 你说得对,我把它简化了。

标签: python filter compression tarfile


【解决方案1】:

您想创建一个通用/可重复使用的函数来过滤给定绝对路径名的文件。我了解仅对存档名称进行过滤是不够的,因为有时可以根据文件的来源来包含或不包含文件。

首先,给你的过滤函数添加一个参数

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

过滤器功能已被 lambda 替换,它传递包含目录的目录名称(否则,将重复根目录)

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

【讨论】:

  • 非常感谢!无论有无完整路径,它都有效:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 2012-08-10
  • 1970-01-01
  • 2013-02-14
  • 2017-08-07
相关资源
最近更新 更多