python - 如何在 shutil.copytree 中编写忽略的回调函数

标签 python file-copying shutil

我对 python 比较陌生。我正在尝试将一个目录复制到另一个保持结构的目录。

我正在使用

    shutil.copytree(src, dst, symlinks=False, ignore=None, 
    copy_function=copy2, ignore_dangling_symlinks=False)

我正在尝试为忽略编写一个回调函数。

我的目标是获取列表中的文件列表,并仅复制那些文件,忽略其余文件。我们如何将列表传递给回调函数?

我写了一个简单的回调函数,但是当我尝试运行 copyTree 函数时出现了一些错误

   def abc(src,names):
    print(src)
    print(names)



    Traceback (most recent call last):
   File "<pyshell#23>", line 1, in <module>
shutil.copytree('D:\Mytest','D:\PythonTestDest3',symlinks=False,ignore=abc)
  File "C:\Python32\lib\shutil.py", line 204, in copytree
if name in ignored_names:
  TypeError: argument of type 'NoneType' is not iterable

最佳答案

ignore 函数的返回需要是要忽略的目录和文件的列表。你没有返回任何东西,它返回 None,所以你得到错误 TypeError: argument of type 'NoneType' is not iterable

这是一个复制文件夹结构和“copy_these”中列出的文件的示例:

import os.path

copy_these = ['a.txt', 'b.txt', 'c.txt']

def ignore_most(folder, files):

    ignore_list = []
    for file in files:
       full_path = os.path.join(folder, file)
       if not os.path.isdir(full_path):
           if file not in copy_these:
               ignore_list.append(file)
    return ignore_list

关于python - 如何在 shutil.copytree 中编写忽略的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7012686/

相关文章:

python - 将文件移动到子目录时出现 os.rename 路径错误

python : summation over all permutations

python - 如何在keras中为tensorboard提供学习率值

python - 使用 spaCy 查找某个单词是否位于两个实体的依赖路径上

python - 如何在 python 中执行相当于 "cp -r"的 linux

Python - 如何将USB(Flash)的内容复制到系统目录

python - 将 BigQuery 脚本的结果返回给 Python 客户端

windows - 如何自动化此 VB 脚本?

windows - 为什么复制到 system32 会自动复制到 sysWOW64?

python - 使用 shutil.make_archive() 创建存档同时排除某些路径