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

使用Python os模块重命名文件时遇FileNotFoundError求助

文件重命名触发FileNotFoundError的解决方案

我尝试在指定目录下重命名文件,规则为将以“000”开头的文件名替换为“district”开头(例如“000_firstname_last_name”改为“district_firstname_lastname”),但执行代码时出现FileNotFoundError,已确认目录路径正确,代码及错误信息如下:

原代码

import os
import shutil

# directory that needs to get sorted:
path = 'C:/Users/paulina.rios/Desktop/test'

# creates a list with directory file names
list = os.listdir(path)

# Goes through each file in the directory
for file in list:

    if file[0:3] == "000":
        split_file1 = file[3:]
        os.rename(file, "district" + split_file1)

错误信息

File "C:\Users\paulina.rios\AppData\Roaming\JetBrains\PyCharmCE2023.1\scratches\scratch.py", line 15, in <module>
    os.rename(file, "district" + split_file1)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '000_11135_03220105_2016-2017.pdf' -> 'district_11135_03220105_2016-2017.pdf'

问题根源

os.listdir(path)返回的仅仅是文件名,并非完整文件路径。当你调用os.rename(file, ...)时,Python会在当前脚本的工作目录里查找目标文件,而不是你指定的path目录,自然找不到对应文件,抛出FileNotFoundError。

修复后的代码

import os

# 目标目录
path = 'C:/Users/paulina.rios/Desktop/test'

# 遍历目录下的所有文件
for file in os.listdir(path):
    # 检查文件名是否以"000"开头
    if file.startswith("000"):
        # 拼接完整的原文件路径和新文件路径
        old_full_path = os.path.join(path, file)
        new_full_path = os.path.join(path, "district" + file[3:])
        # 执行重命名操作
        os.rename(old_full_path, new_full_path)

额外优化建议

  • 用file.startswith("000")替代file[0:3] == "000":代码更简洁,同时避免了文件名长度不足3位时引发的索引错误。
  • 移除不必要的shutil导入:os.rename完全可以完成文件重命名操作。
  • 避免使用list作为变量名:它是Python内置类型,容易引发命名冲突,直接遍历os.listdir(path)的结果即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 08:55:20