Python shutil.copytree() 有办法跟踪复制状态吗?
我有很多光栅文件(超过600个),它们分散在不同的文件夹里,我需要把这些文件连同它们的文件夹结构一起复制到一个新的位置。有没有办法在使用shutil.copytree()时跟踪复制的进度?通常如果是单个文件,我会用下面的代码,但我不太确定怎么用shutil.copytree()来做到这一点:
for currentFolder, subFolder, fileNames in os.walk(sourceFolder):
for i in fileNames:
if i.endswith(".img"):
print "copying {}".format(i)
shutil.copy(os.path.join(currentFolder,i), outPutFolder)
3 个回答
12
另一个选择是使用 copytree
的 copy_function
参数。这样做的好处是,它会在每个文件被复制时调用,而不是每个文件夹。
from shutil import copytree,copy2
def copy2_verbose(src, dst):
print('Copying {0}'.format(src))
copy2(src,dst)
copytree(source, destination, copy_function=copy2_verbose)
15
是的,可以通过利用传入的'ignore'参数的函数名来实现类似的功能。实际上,Python文档的示例部分就有类似的内容:
https://docs.python.org/2/library/shutil.html#copytree-example
下面也贴上了示例代码:
from shutil import copytree
import logging
def _logpath(path, names):
logging.info('Working in %s' % path)
return [] # nothing will be ignored
copytree(source, destination, ignore=_logpath)