我想在使用tarfile(python3.4)创建tar(gz)文件时过滤子目录(跳过它们)。你知道吗
磁盘上的文件:
试图用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()
您希望创建一个通用/可重用函数,以过滤给定绝对路径名的文件。我理解,仅对存档名称进行过滤是不够的,因为有时可以包含文件,也可以不包含文件,这取决于文件的来源。你知道吗
首先,在filter函数中添加一个参数
然后,将“添加到存档”代码行替换为:
filter函数已被一个
lambda
替换,该函数传递include目录的目录名(否则,将重复根目录)现在您的filter函数知道根目录,您可以按绝对路径进行过滤,从而允许您在代码中的多个位置重用filter函数。你知道吗
相关问题 更多 >
编程相关推荐