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