Python shutil.copytree()可以跟踪复制的状态

Tsv*_*Gis 4 python copy

我在目录中有很多光栅文件(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)
Run Code Online (Sandbox Code Playgroud)

nbe*_*hat 7

另一种选择是使用 的copy_function参数copytree。优点是它将为复制的每个文件而不是每个文件夹调用它。

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)
Run Code Online (Sandbox Code Playgroud)


use*_*927 6

是的,通过利用传入'ignore'参数的函数名称,可以实现这样的功能.事实上,在python docs的示例部分中给出了类似这样的内容: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)
Run Code Online (Sandbox Code Playgroud)