You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的shutil无需判断类型实现文件与目录复制

问题:用shutil实现自动适配文件/目录的复制功能

需求与当前实现

我想用Python的shutil模块实现Shell命令cp ~/.config/profiles/* $HOME的功能,但找不到能自动判断目标是文件还是目录的最优方法,目前只能编写带条件判断的代码:

from pathlib import Path
from shutil import copytree, copy

for file_path in Path().home().joinpath(".config/profiles").iterdir():
    filename = str(file_path).split("/")[-1]
    destination = Path.home().joinpath(filename)
    if not destination.exists() and file_path.exists():
        copytree(src=file_path, dst=destination) if file_path.is_dir() else copy(src=file_path, dst=destination)

    print(destination, file_path)

发现shutil.move的特性

原本以为这是shutil的设计限制,但发现shutil.move方法可以自动处理文件或目录的移动操作:

shutil.move(src, dst, copy_function=copy2)¶
Recursively move a file or directory (src) to another location and return the destination.

疑问

请问如何无需条件判断就能复制文件或目录到目标路径?我在shutil中未找到相关方法。

自行实现的copyall函数

更新: 我自行编写了期望在shutil中找到的copyall函数:

from pathlib import Path
from shutil import copytree, copy

def copyall(src: str, dst: str):
    """Copy all files or/and directories from one directory inside of another directory"""
    if Path(src).is_dir() and Path(dst).is_dir():
        for file_path in Path(src).iterdir():
            if file_path.is_dir():
                copytree(file_path, Path(dst) / file_path.name)
            else:
                copy(file_path, Path(dst) / file_path.name)

内容的提问来源于stack exchange,提问作者Alex Zolotarov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:33:26