【问题标题】:Ignore multiple identical subdirectories with shutil使用 shutil 忽略多个相同的子目录
【发布时间】:2019-12-15 20:04:21
【问题描述】:

假设我有以下文件夹,名为 local,我想使用 python 3.7shutil 库对其进行递归复制。 local 文件夹始终具有相同的内部结构。

.
├── local/
    ├── A/
    |   ├── img/     
    |   |    ├── 1.jpg
    |   |    ├── ...
    |   |    └── n.jpg     
    |   |
    |   └── txt/
    |        ├── text_1.txt
    |        ├── ...
    |        └── text_n.txt
    ├── B/
    .   ├── img/     
    .   |    ├── 1.jpg
    .   |    ├── ...
        |    └── n.jpg     
        |
        └── txt/
             ├── text_1.txt
             ├── ...
             └── text_n.txt

使用shutil库和它的copy方法,如果想得到下面的remote结构,怎么写ignore_patterns参数(递归忽略每个子文件夹中的img文件夹 ):

.
├── remote/
    ├── A/
    |   └── txt/
    |        ├── text_1.txt
    |        ├── ...
    |        └── text_n.txt
    ├── B/
    .   └── txt/
    .        ├── text_1.txt
    .        ├── ...
             └── text_n.txt

天真地,我尝试了shutil.copytree('local', 'remote', ignore=shutil.ignore_patterns('local/*/img')),但没有成功。

【问题讨论】:

    标签: python copy shutil


    【解决方案1】:

    从您发布的代码看来,您的 localremote 目录与您的脚本相关,那么以下内容如何:

    from shutil import copytree, ignore_patterns
    
    # also use an absolute path below, prefix with r'<Absolute Path...>'
    source = 'local' 
    destination = 'remote'
    
    copytree(
        src=source,
        dst=destination,
        ignore=ignore_patterns('img')
    )
    

    shutil 模块已经包含了ignore_patterns() 函数,所以不需要自己创建函数...

    在路径前加上 r'' 会创建一个原始字符串,它将反斜杠视为文字字符,因此您无需转义它们。

    【讨论】:

      猜你喜欢
      • 2012-02-07
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多