简体   繁体   English

os.rename返回winerror 2

[英]os.rename returning winerror 2

I'm trying to a script to rename to the date that it was sent as an email(which is the first part of the script but doesn't matter for this part) then to rename, and sort it into a 'Complete' folder. 我正在尝试将脚本重命名为以电子邮件发送的日期(这是脚本的第一部分,但对这一部分无关紧要),然后重命名并将其分类到“完整”文件夹中。 This is what my code looks like 这就是我的代码

Edit - I have all the imported stuff way up at the top and i didnt show it, but i assume i have the right stuff imported if you would like to see just ask 编辑-我将所有导入的内容放在顶部,但我没有显示出来,但是我想我已经导入了正确的内容,如果您想看看就问一下

dir5 = "C:\\Users\\Michael D\\Documents\\Test\\AmLit"
dir6 = "C:\\Users\\Michael D\\Documents\\Test\\History"
dir7 = "C:\\Users\\Michael D\\Documents\\Test\\MultiLit"
dir8 = "C:\\Users\\Michael D\\Documents\\Test\\Physics"
dir5_final = "C:\\Users\\Michael D\\Documents\\TestMove\\AmLit"
dir6_final = "C:\\Users\\Michael D\\Documents\\TestMove\\History"
dir7_final = "C:\\Users\\Michael D\\Documents\\TestMove\\MultiLit"
dir8_final = "C:\\Users\\Michael D\\Documents\\TestMove\\Physics"


now = datetime.datetime.now()
now1 = (str(now.day) + '/' + str(now.month) + '/' + str(now.year))

dir5_files = os.listdir(dir5)
dir6_files = os.listdir(dir6)
dir7_files = os.listdir(dir7)
dir8_files = os.listdir(dir8)

for f in dir5_files:
    if (f.startswith("A") or f.startswith("a")):
        os.rename(f, now1 + " " + f)

but i keep getting this error 但我不断收到这个错误

 RESTART: C:/Users/Michael D/Documents/Coding/Schoolwork Email/Email Sender Beta 1.7.21.9.16.py 
Traceback (most recent call last):
  File "C:/Users/Michael D/Documents/Coding/Schoolwork Email/Email Sender Beta 1.7.21.9.16.py", line 148, in <module>
    os.rename(f, now1 + " " + f)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'A Test.txt' -> '21/9/2016 A Test.txt'

any thoughts as to what I'm doing wrong? 关于我在做什么错有什么想法吗?

2 errors: 2个错误:

  1. You are not in the current directory 您不在当前目录中

  2. You just cannot have slashes in the names. 名称中不能包含斜线。 The filesystem won't allow it as it is (alternately) used to separate path parts. 文件系统将不允许使用它,因为它(另外)用于分隔路径部分。

First, generate the date directly with underscores: 首先,直接使用下划线生成日期:

now1 = (str(now.day) + '_' + str(now.month) + '_' + str(now.year))

Then replace 然后更换

os.rename(f, now1 + " " + f)

by 通过

os.rename(os.path.join(dir5,f), os.path.join(dir5,now1.replace("/","_") + " " + f))

and A Test.txt would be renamed to 21_9_2016 A Test.txt in the directory you specified. A Test.txt将被重新命名为21_9_2016 A Test.txt在你指定的目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM