我对 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/