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

Windows下shutil.copytree报错:FileExistsError[WinError 183]

解决Windows下shutil.copytree触发FileExistsError的问题

我之前在Windows上用shutil.copytree的时候也踩过这个坑——这个错误的核心原因是:shutil.copytree默认要求目标目录必须不存在,哪怕目标目录是空的也不行,而Windows系统对目录创建的校验更严格,直接抛出了WinError 183。

给你几个可行的解决方案,根据你的需求选就行:

方案1:删除已存在的目标目录后再复制(适合完全覆盖场景)

如果你确定要把目标目录的内容全部替换成源目录的内容,可以先删除已存在的目标目录,再执行复制:

import os.path
import shutil

src = os.path.join("..", "_build")
dst = "_build"
print("Copying {} to {}".format(src, dst))

if os.path.exists(dst):
    # 递归删除整个目标目录
    shutil.rmtree(dst)
    print(f"Removed existing directory: {dst}")

shutil.copytree(src, dst)
print(f"Successfully copied {src} to {dst}")

⚠️ 注意:shutil.rmtree会彻底删除目标目录及其所有内容,使用前要确认目标目录里的内容没有保留必要。

方案2:合并源目录到已存在的目标目录(适合增量更新场景)

如果不想删除目标目录,而是要把源目录的内容合并进去(类似Linux的cp -r src/* dst/),可以自己写一个递归复制的函数:

import os
import shutil

def merge_dirs(src, dst):
    # 确保目标目录存在,不存在则创建
    os.makedirs(dst, exist_ok=True)
    
    for item_name in os.listdir(src):
        src_item = os.path.join(src, item_name)
        dst_item = os.path.join(dst, item_name)
        
        if os.path.isdir(src_item):
            # 递归处理子目录
            merge_dirs(src_item, dst_item)
        else:
            # 复制文件,已存在则直接覆盖
            shutil.copy2(src_item, dst_item)
            print(f"Copied file: {src_item} -> {dst_item}")

src = os.path.join("..", "_build")
dst = "_build"
print("Merging contents from {} to {}".format(src, dst))

merge_dirs(src, dst)
print("Merge completed successfully")

这个方法会逐个处理源目录里的文件和子目录,文件存在就覆盖,子目录不存在就创建,存在则继续合并。

方案3:使用Python 3.8+新增的参数(最简洁)

从Python 3.8开始,shutil.copytree新增了dirs_exist_ok参数,设置为True就允许目标目录存在,直接合并内容:

import os.path
import shutil

src = os.path.join("..", "_build")
dst = "_build"
print("Copying {} to {}".format(src, dst))

# dirs_exist_ok=True 允许目标目录已存在
shutil.copytree(src, dst, dirs_exist_ok=True)
print(f"Successfully copied {src} to {dst}")

这是最省心的方法,前提是你的Python版本在3.8及以上。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:46:57