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

Python重命名文件夹文件报错[WinError 2],寻求解决方法

问题排查与解决

错误原因分析

  • 文件路径不完整:os.listdir(directory)返回的只是目标文件夹内的文件名(比如PBIItemsResults132.csv),但os.rename默认在当前Python脚本的工作目录下查找文件,而非你指定的directory目录,因此会出现找不到文件的报错。
  • 文件名处理无效:strip("0123456789 ")仅会删除字符串首尾的数字和空格,你的示例文件名PBIItemsResults132.csv首尾无此类字符,导致处理后的文件名和原文件名完全一致,这也是错误信息里新旧文件名相同的原因。

修正后的代码

情况1:仅删除文件名首尾的数字和空格(保留中间数字)

先拼接完整路径,确保os.rename能准确定位文件:

import os

directory = r"C:\Users\jhonatta-silva\Downloads"

for file in os.listdir(directory):
    if file.startswith("PBI"):
        # 拼接完整的源文件路径和目标文件路径
        src_path = os.path.join(directory, file)
        # 处理文件名:删除首尾的数字和空格
        new_filename = file.strip("0123456789 ")
        dst_path = os.path.join(directory, new_filename)
        # 避免无意义重命名及重名覆盖(可选但推荐)
        if src_path != dst_path:
            os.rename(src_path, dst_path)

情况2:删除文件名中所有的数字和空格

如果需求是删掉文件名里全部数字和空格(包括中间的),可以用正则表达式替换:

import os
import re

directory = r"C:\Users\jhonatta-silva\Downloads"

for file in os.listdir(directory):
    if file.startswith("PBI"):
        src_path = os.path.join(directory, file)
        # 替换所有数字和空格为空字符串
        new_filename = re.sub(r'[0-9\s]', '', file)
        dst_path = os.path.join(directory, new_filename)
        if src_path != dst_path:
            os.rename(src_path, dst_path)

注意事项

  • 运行脚本前建议备份目标文件夹内的文件,避免误操作导致文件丢失。
  • 添加if src_path != dst_path:判断,既能避免无意义的重复重命名,也能减少重名文件被覆盖的风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:05:31