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

Python:os.path.isfile在shutil.copyfile执行前返回True(目标文件不存在)

问题排查与解决方案

按以下步骤逐一排查,应该能解决你的问题:

1. 确认目标路径的真实指向

你看到的tgt路径可能和代码实际检查的不是同一个——尤其是Jupyter环境中,工作目录很容易和预期不符。把打印tgt的代码改成:

print("目标绝对路径:", os.path.abspath(tgt))

对比你手动删除的文件路径,看是否完全一致。另外,CSV里的路径可能带了多余空格或换行符,给tgt做个清理:

tgt = row['Target'].strip()

2. 检查CSV是否有重复目标行

如果CSV里有多条记录指向同一个tgt,第一次循环已经完成复制,第二次循环检查时文件自然存在。可以在循环里打印当前行号:

print(f"正在处理第 {index} 行")

确认是否重复处理了同一个目标路径。

3. 补全缺失的模块导入

你的代码里用了filecmp.cmp但没导入该模块,虽然Jupyter可能缓存了之前的导入,但正式运行会报错,补上:

import filecmp

4. 单独测试单条路径

跳出循环单独测试某一行,快速定位问题:

# 取CSV第一行测试
test_src = df.iloc[0]['Source'].strip()
test_tgt = df.iloc[0]['Target'].strip()

# 手动删除test_tgt对应的文件后执行
print(os.path.isfile(test_tgt))  # 正常应该返回False
shutil.copyfile(test_src, test_tgt)
print(os.path.isfile(test_tgt))  # 现在返回True

修正后的参考代码

import pandas as pd
import os
import shutil
import filecmp  # 补上缺失的导入

df = pd.read_csv(file_path)

for index, row in df.iterrows():
    src = row['Source'].strip()
    tgt = row['Target'].strip()

    # 先检查源文件是否存在,避免报错
    if not os.path.isfile(src):
        print(f"第 {index} 行:源文件 {src} 不存在,跳过")
        continue

    tgt_exist = os.path.isfile(tgt)
    print(f"第 {index} 行 - 目标文件存在?{tgt_exist},路径:{os.path.abspath(tgt)}")
    
    if tgt_exist and filecmp.cmp(src, tgt):
        print("Target : Exists, same.")
    elif tgt_exist and not filecmp.cmp(src, tgt):
        print("Target : Exists, not same. Will not copy.")
    else:
        print("Target : Not exists. Copying...")
        shutil.copyfile(src, tgt)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:24:58