我对python比较陌生。我正在尝试将一个目录复制到另一个保持结构的目录中。
我正在使用
shutil.copytree(src, dst, symlinks=False, ignore=None,
copy_function=copy2, ignore_dangling_symlinks=False)我正在试着为ignore写一个回调函数。
我的目标是获取列表中的文件列表,并且只复制这些文件,而忽略其余文件。我们如何将列表传递给回调函数?
我编写了一个简单的回调函数,但在尝试运行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发布于 2011-08-10 22:54:47
ignore函数的返回值需要是要忽略的目录和文件的列表。您没有返回任何内容,这将返回None,因此您将得到错误TypeError: argument of type 'NoneType' is not iterable。
下面的示例将复制文件夹结构和‘copy _ the’中列出的文件:
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发布于 2011-08-10 22:49:18
shutil模块提供了一个ignore_patterns函数。
此工厂函数创建一个函数,该函数可用作copytree()的忽略参数的可调用函数,忽略与所提供的glob样式模式之一匹配的文件和目录。
模块页面也显示了a couple of examples。
发布于 2011-08-10 22:51:35
ignore回调函数应返回与不应复制的'src‘目录相关的名称列表。
您的示例回调不返回任何内容(即。无)。然后,需要一个列表的copytree会尝试遍历它。既然它不能,你就会得到那个异常。
https://stackoverflow.com/questions/7012686
复制相似问题