Python tarfile 和排除

标签 python tarfile

这是 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/

相关文章:

python - 在python中,如果提取一个tar.gz文件,如何获取或设置结果文件的名称

python - 如何通过名称而不是 ID 获取表情符号并将其添加到消息中?不和谐.py

python - 使用 python 3 中的 matplotlib 在堆叠条形图中堆叠多列

python - obj_create 无法在 tastypie 中工作

python - Django 模板 : static files in app directory

python - 如何用只包含数据但没有文件名的python解压xz文件?

python - 开箱即用的示例不适用于 python 3.3 预期字节 str 找到

使用 SSH 或 FTP 压缩远程目录的 Pythonic 方法

Python:使用 tarfile 从 TAR 存档中删除文件

python - pandas 可以在存档中读取和存档吗?