在Python中重命名文件:WindowsError:[错误2]系统找不到指定的文件 [英] rename file in Python: WindowsError: [Error 2] The system cannot find the file specified

查看:189
本文介绍了在Python中重命名文件:WindowsError:[错误2]系统找不到指定的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to rename a file in a folder and i keep getting the error that the file is not there....

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:/用户/xxxxxx/桌面/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'] 追溯(最近一次通话): 在第24行中输入文件"C:/Users/sabaja/Desktop/Paython/Python3/pbx.py" os.rename('EZShift_WeeklyPerDayScheduleReport_Export.xlsx',"EZShift_" + time_srt +".xlsx") WindowsError:[错误2]系统找不到指定的文件

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完成的过程

Process finished with exit code 1

推荐答案

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

your filenames from os.listdir are relative paths (os.listdir returns the filenames onla); they will be searched for in your current working directory which is os.getcwd() (that will not be changed just because you name a variable working_dir)

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

you need to os.path.join(working_dir, filename) to get absolute paths in order to access (and rename) your files.

您可以执行以下操作:

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中重命名文件:WindowsError:[错误2]系统找不到指定的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆