【问题标题】:How to exclude specific subfolders from the generated tar file?如何从生成的 tar 文件中排除特定的子文件夹?
【发布时间】:2019-12-16 22:28:38
【问题描述】:

我正在使用 Python 3 和 tarfile 模块来压缩一些文件夹(带有子文件夹)。我需要做的:设置几个子文件夹从最终的 tar 文件中排除。

例如,假设我的文件夹看起来像:

dir/
├── subdirA
│   ├── subsubdirA1
│   │   └── fileA11.txt
│   │   └── fileA12.txt
│   ├── subsubdirA2
│   │   └── fileA21.txt
│   │   └── fileA22.txt
│   └── fileA.txt
├── subdirB
│   ├── subsubdirB1
│   │   └── fileB11.txt
│   │   └── fileA12.txt
│   ├── subsubdirB2
│   │   └── fileB21.txt
│   │   └── fileB22.txt
│   └── fileB.txt
└── main.txt

现在,我说我想在dir/ 中包含除subsubdirA2subsubdirB2 的内容之外的所有内容。基于this answer,我试过了:

EXCLUDE_FILES = ['/subdirA/subsubdirA2', '/subdirB/subsubdirB2']
mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)

或者:

EXCLUDE_FILES = ['/subdirA/subsubdirA2/*', '/subdirB/subsubdirB2/*']
mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)

或者:

EXCLUDE_FILES = ['/subdirA/subsubdirA2/*.*', '/subdirB/subsubdirB2/*.*']
mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)

我还尝试了上述三个选项的变体,其中子文件夹路径开始时没有 /dir/dir。没有任何效果 - 一直以来,dir 中的所有内容都包括在内。

如何正确地从我想要生成的 tar 文件中排除特定的子文件夹?如果需要不同的模块/库而不是 tarfile,那很好。

【问题讨论】:

  • 适用于 linux??...因为可能与子进程(shell 库)和 python 可以工作
  • 我认为x.nameEXCLUDE_FILES 列表中的任何项目都不匹配,因为/file/path/* 被视为名称为* 的文件而不是正则表达式匹配
  • @saurjog 但这不适用于我给出的其他示例,对吧?
  • @JorgetMillani,为迟到的回复道歉。请看下面我的回答。我之前的评论适用于您给出的所有示例。

标签: python python-3.x tar subdirectory tarfile


【解决方案1】:

我没有找到你需要的关于 tarfile 的参考资料,但是你可以像这样使用线程和包含 shell 命令:

import subprocess

exclude=['dir/subdirA/subsubdirA2','dir/subdirA/subsubdirA1','dir/subdirA/text.tx']
excludeline=''
for x in exclude:
    excludeline += ' --exclude '+x
# cmd has tar command
cmd='tar -czvf dir.tar dir  '+ excludeline
print(cmd)
process = subprocess.Popen(cmd,shell=True,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result=process.stdout.readlines()
# All files were compressed
if len(result) >= 1:
    for line in result:
        print(line.decode("utf-8"))

在这个例子中 cmd 有值:

cmd = tar -czvf dir.tar dir   --exclude dir/subdirA/subsubdirA2 --exclude dir/subdirA/subsubdirA1 --exclude dir/subdirA/text.tx

【讨论】:

    【解决方案2】:

    我认为您使用的EXCLUDE_FILES 应该通过模式匹配与文件名匹配。以下是我的做法:

    import re, os    
    EXCLUDE_FILES = ['/subdirA/subsubdirA2/*', '/subdirB/subsubdirB2/*']
    pattern = '(?:% s)' % '|'.join(EXCLUDE_FILES) #form a pattern string
    

    为了对模式使用过滤器,我们将使用re.match

    mytarfile.add(..., filter=lambda x: None if re.match(pattern, x.name) else x)
    

    如果file.name 匹配EXCLUDE_FILES 中指定的任何模式,我们会排除该文件。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      相关资源
      最近更新 更多