Python shutil.copytree() 有办法跟踪复制状态吗?

6 投票
3 回答
10679 浏览
提问于 2025-04-28 21:51

我有很多光栅文件(超过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 个回答

3

Python 2.7

你可以在这里找到Python 2.7的shutil的源代码。你可以复制这段源代码,然后在第282行添加print name

Python 3.4

你可以在这里找到Python 3.4的shutil的源代码。你可以复制这段源代码,然后在第307行添加print name

12

另一个选择是使用 copytreecopy_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)

撰写回答