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

Python根据DataFrame值移动文件报错求助:文件未找到/类型错误

解决Python文件移动的两个常见错误

错误1:FileNotFoundError(空路径)

原因分析

出现这个错误说明代码中拿到的源路径或目标路径是空字符串,大概率是这两种情况:

  • DataFrame的image_path或ipath列存在空值行
  • 读取列名时拼写错误(比如大小写、多打少打字符),导致拿到空的Series值

解决步骤

  1. 先排查数据有效性:
    import pandas as pd
    df = pd.read_csv("你的数据文件.csv")
    # 查看列的数据类型和非空计数
    print(df[['image_path', 'ipath']].info())
    # 找出空值行
    print(df[df['image_path'].isna() | df['ipath'].isna()])
    
  2. 过滤无效行后再执行移动:
    import os
    # 删掉有空值的行
    df_clean = df.dropna(subset=['image_path', 'ipath'])
    # 循环移动文件,同时检查源文件是否存在
    for _, row in df_clean.iterrows():
        src = row['image_path']
        dst = row['ipath']
        if os.path.exists(src):
            os.rename(src, dst)
        else:
            print(f"跳过不存在的源文件:{src}")
    

错误2:rename: dst should be string, bytes or os.PathLike, not int

原因分析

这个错误是因为你把循环的索引值当成了目标路径传给了os.rename的第二个参数,比如错误代码类似这样:

# 错误示例
for i, src in enumerate(df['image_path']):
    os.rename(src, i)  # 这里把索引i(整数)当成了目标路径

解决步骤

要确保同时获取对应的源路径和目标路径,推荐两种写法:

  1. 用zip同时遍历两列:
    for src, dst in zip(df['image_path'], df['ipath']):
        # 先判断路径是否为有效字符串且源文件存在
        if isinstance(src, str) and isinstance(dst, str) and os.path.exists(src):
            os.rename(src, dst)
        else:
            print(f"跳过无效路径组合:源={src},目标={dst}")
    
  2. 用iterrows遍历行:
    for idx, row in df.iterrows():
        src = row['image_path']
        dst = row['ipath']
        if isinstance(src, str) and isinstance(dst, str) and os.path.exists(src):
            os.rename(src, dst)
        else:
            print(f"第{idx}行路径无效,跳过")
    

额外注意事项

  • 虽然你说已创建目标目录,还是可以加一行代码确保万无一失:os.makedirs(os.path.dirname(dst), exist_ok=True),放在os.rename之前
  • 打印每次循环的src和dst,方便调试时确认路径是否正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:55:13