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

如何解决Python重命名文件时的FileNotFoundError: [WinError 3]?

解决Python重命名文件时的FileNotFoundError问题

你遇到的问题核心是路径写错了:代码里的/Downloads/Test.xlsx指向的是系统根目录下的Downloads文件夹,而Windows系统里根本不存在这个路径——你实际要访问的是当前用户家目录下的Downloads(也就是~/Downloads对应的真实路径)。

给你几个可行的解决办法:

方法1:用os.path.expanduser()解析用户家目录

这个方法能自动把~转换成当前用户的家目录路径,跨系统通用:

import os
from datetime import datetime

current_timestamp = datetime.today().strftime('%d-%b-%Y')
# 解析~为实际用户家目录路径
old_name = os.path.expanduser(r"~/Downloads/Test.xlsx")
new_name = os.path.expanduser(r"~/Downloads/Test_" + current_timestamp + ".xlsx")
os.rename(old_name, new_name)

方法2:使用pathlib模块(推荐,Python3.4+)

pathlib提供了更直观的路径操作方式,代码更简洁易读:

from pathlib import Path
from datetime import datetime

current_timestamp = datetime.today().strftime('%d-%b-%Y')
# 获取用户家目录下的Downloads文件夹
downloads_dir = Path.home() / "Downloads"
old_file = downloads_dir / "Test.xlsx"
new_file = downloads_dir / f"Test_{current_timestamp}.xlsx"
old_file.rename(new_file)

额外注意事项

  • 先确认Test.xlsx确实存在于你的Downloads文件夹中,文件名没有拼写错误(包括空格、大小写,Windows虽然不区分大小写,但尽量和实际文件名保持一致)
  • 运行脚本时确保你对该文件有读写权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 10:45:35