我正在尝试重命名文件夹中的文件,但我不断收到文件不存在的错误......
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/