【发布时间】: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