这是 Python 文档的摘录:
If exclude is given it must be a function that takes one filename argument and returns a boolean value. Depending on this value the respective file is either excluded (True) or added (False).
我必须承认我不知道那是什么意思。
此外:
Deprecated since version 2.7: The exclude parameter is deprecated, please use the filter parameter instead. For maximum portability, filter should be used as a keyword argument rather than as a positional argument so that code won’t be affected when exclude is ultimately removed.
好的...以及“过滤器”的定义:
If filter is specified it must be a function that takes a TarInfo object argument and returns the changed TarInfo object. If it instead returns None the TarInfo object will be excluded from the archive.
...回到原点:)
我真正需要的是一种将排除数组(或“:”分隔字符串)传递给 tarfile.add 的方法。
如果你试图解释 PyDocs 中的那些段落是什么,我不介意。
附言:
这只是我的想法:
- 制作源目录内容列表的数组
- 弹出排除
- 对剩余的单个数组成员执行 tar.add
但是,我希望以更文明的方式完成
最佳答案
If exclude is given it must be a function that takes one filename argument and returns a boolean value. Depending on this value the respective file is either excluded (True) or added (False).
例如,如果您想排除所有以字母 'a' 开头的文件名,您可以这样做...
def exclude_function(filename):
if filename.startswith('a'):
return True
else:
return False
mytarfile.add(..., exclude=exclude_function)
对于您的情况,您需要类似...
EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']
def exclude_function(filename):
if filename in EXCLUDE_FILES:
return True
else:
return False
mytarfile.add(..., exclude=exclude_function)
...可以简化为...
EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']
mytarfile.add(..., exclude=lambda x: x in EXCLUDE_FILES)
更新
TBH,我不会太担心弃用警告,但如果你想使用新的 filter
参数,你需要类似...
EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']
def filter_function(tarinfo):
if tarinfo.name in EXCLUDE_FILES:
return None
else:
return tarinfo
mytarfile.add(..., filter=filter_function)
...可以简化为...
EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']
mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)
关于Python tarfile 和排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16000794/