有些小脚本就是会反复把一份目录拷到目标路径。
环境:Python 3.8+,只用标准库。保存为 copytree-demo.py:
from pathlib import Path
from tempfile import TemporaryDirectory
from shutil import copytree
with TemporaryDirectory() as src, TemporaryDirectory() as dst:
src_root = Path(src)
dst_root = Path(dst)
(src_root / 'a.txt').write_text('hello', encoding='utf-8')
(src_root / 'sub').mkdir()
(src_root / 'sub' / 'b.txt').write_text('world', encoding='utf-8')
target = dst_root / 'backup'
copytree(src_root, target, dirs_exist_ok=True)
copytree(src_root, target, dirs_exist_ok=True)
print(sorted(str(p.relative_to(target)) for p in target.rglob('*') if p.is_file()))
这样目标目录已经存在时也能继续拷,不用先手动判断一遍。