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

Python中如何移动文件并覆盖目标文件夹内的同名文件?

移动文件并自动覆盖同名文件的Python实现方案

shutil.move() 触发目标路径已存在的报错,是因为跨磁盘分区移动文件时,该方法的底层逻辑是先复制源文件到目标路径、再删除源文件,该流程默认不允许覆盖已存在的文件。同磁盘分区下移动文件是直接修改文件系统索引,通常不会触发该错误。

下面是三种可行的实现方案:

方案1:先删除目标同名文件再执行移动

适合需要兼容所有Python版本、且对操作原子性要求不高的场景

import os
import shutil

# 替换为你的源文件路径
min_file = "C:/source/g.txt"
# 替换为你的目标文件夹路径
d_folder = "C:/"
# 拼接得到目标文件完整路径
target_file = os.path.join(d_folder, os.path.basename(min_file))

# 目标文件存在则先删除
if os.path.exists(target_file):
    os.remove(target_file)

# 执行移动
shutil.move(min_file, d_folder)
print("File is moved successfully to: ", target_file)

方案2:使用os.replace()直接覆盖(推荐)

os.replace() 是Python内置的原子操作方法,默认直接覆盖目标路径的同名文件,跨平台兼容,不会出现中间状态的文件损坏问题,是最优选择

import os

min_file = "C:/source/g.txt"
d_folder = "C:/"
target_file = os.path.join(d_folder, os.path.basename(min_file))

# 直接执行移动+覆盖操作
os.replace(min_file, target_file)
print("File is moved successfully to: ", target_file)

方案3:先复制覆盖再删除源文件

适合跨磁盘分区移动、且使用os.replace()出现兼容问题的场景,shutil.copy2()会保留文件的元数据(修改时间、权限等)

import os
import shutil

min_file = "C:/source/g.txt"
d_folder = "C:/"
target_file = os.path.join(d_folder, os.path.basename(min_file))

# 复制源文件到目标路径,自动覆盖同名文件
shutil.copy2(min_file, target_file)
# 删除源文件完成移动
os.remove(min_file)
print("File is moved successfully to: ", target_file)

内容的提问来源于stack exchange,提问作者Kaung Sat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:18:02