Python: 递归复制一批目录

Python: recursively copy batch of directories

我正在尝试创建一个脚本,允许我们输入一组目录路径,然后递归地将这些目录复制到新计算机。这是针对我们与员工的计算机更新流程。我知道我可以使用 shutil 将源复制到目标,但我想更进一步,收集所有源目录,然后使用相同的目录路径将它们复制到目标硬盘。

例如: src = G:\users\%specificuser%\Documents dst = C:\users\%specificuser%\Documents

我不想每次都输入来源和目的地。所以我想我首先需要知道这在 Python 中是否可行。如果是这样,我从哪里开始?

怎么样:

shutil.copytree(src, dst)

或者实现你自己的复制树,它会在需要时遍历创建它们的目录(避免 "The destination directory must not already exist." 的问题,正如评论中指出的那样),一种单向同步:

import os, os.path, shutil

src="G:\TestCopy"
dst="D:\TestCopy"

def copy_tree(srcpath, dstpath):
    print(srcpath)
    if not os.path.exists(dstpath):
        os.makedirs(dstpath)
    for candidate in os.listdir(srcpath):
        srccan = os.path.join(srcpath, candidate)
        dstcan = os.path.join(dstpath, candidate)
        if os.path.isdir(srccan):
            copy_tree(srccan, dstcan)
        else:
            shutil.copyfile(srccan, dstcan)

copy_tree(src, dst)

如果你想根据部分路径中的特定用户构造用户字符串,os.path.join 擅长于此:

specificuser = "fred"
src = os.path.join("G:\users", specificuser, "Documents")
dst = os.path.join("D:\users", specificuser, "Documents")
print(src)
print(dst)

输出:

G:\users\fred\Documents
D:\users\fred\Documents