本文介绍了在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")

以退出代码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]系统找不到指定的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 00:55