python - 在Python中重命名文件: WindowsError: [Error 2] The system cannot find the file specified

标签 python excel

我正在尝试重命名文件夹中的文件,但我不断收到文件不存在的错误......

import os
import time
from os.path import isfile, join


working_dir = ('C:/Users/XXXXX/Desktop')
only_file = [f for f in os.listdir(working_dir) if os.path.isfile(os.path.join(working_dir, f))]
print only_file

time_srt = time.strftime("%d_%m_%Y")

if 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx' in only_file:
    os.rename('EZShift_WeeklyPerDayScheduleReport_Export.xlsx', "EZShift_" + time_srt + ".xlsx")

C:\Python27\python.exe C:/Users/xxxxxx/Desktop/Paython/Python3/pbx.py ['xxxxxx.jpg', 'xxxx.zip', 'xxxx.xlsx', 'xxx.pdf', 'xxx.MOV', 'xx.MOV', 'xxxxx_18_12_2016.xlsx', 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx','Test_EZShift_WeeklyPerDayScheduleReport_Export.xlsx'] Traceback (most recent call last): File "C:/Users/sabaja/Desktop/Paython/Python3/pbx.py", line 24, in os.rename('EZShift_WeeklyPerDayScheduleReport_Export.xlsx', "EZShift_" + time_srt + ".xlsx") WindowsError: [Error 2] The system cannot find the file specified

进程已完成,退出代码为 1

最佳答案

来自 os.listdir 的文件名是相对路径(os.listdir 返回 onla 上的文件名);它们将在您当前的工作目录 os.getcwd() 中搜索(该目录不会仅仅因为您命名变量 working_dir 而改变)

您需要os.path.join(working_dir, filename)获取绝对路径以便访问(和重命名)您的文件。

你可以这样做:

import os.path

if 'EZShift_WeeklyPerDayScheduleReport_Export.xlsx' in only_file:
    old_path = os.path.join(working_dir, "EZShift_WeeklyPerDayScheduleReport_Export.xlsx")
    new_path = os.path.join(working_dir, "EZShift_" + time_srt + ".xlsx")
    os.rename(old_path, new_path)

关于python - 在Python中重命名文件: WindowsError: [Error 2] The system cannot find the file specified,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41919034/

相关文章:

python - 为什么 scipy.signal.welch 会抑制零频率?

c# - 图表的 SetSourceData 返回数据透视表的 HRESULT E_FAIL (Excel C#)

c# - 应用程序对象正在关闭异常

excel - 如何在 Excel 中解决此依赖数据验证的字符串公式?

C#技巧——通过字符串获取常量值

VBA:如何在应用文本时考虑 WEEKNUM 2019 值

python - 使用 python 和 selenium 以某种语言(英语)抓取谷歌代码段文本

python - 如何使用不同的数据多次执行相同的查询?

python - SQLAlchemy - 通过其子项查询父项,过滤连接以匹配列表中的每个子项

Python:在运行子进程时处理中断