0

我想在使用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

所以因为/home/myuser/temp/test1/thing元素在exclude_dir_fullpath,过滤方法应该排除这个文件,但不能因为过滤方法得到test1/thing/bar.jpg

如何在过滤器方法中访问 tarfile.add() 的“名称”参数?

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

1 回答 1

0

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

首先,为您的过滤器函数添加一个参数

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传递包含目录的目录名称的a(否则,将重复根目录)

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

于 2016-09-11T18:57:59.583 回答