os.rename返回winerror 2

时间:2016-09-21 15:49:26

标签: python python-3.x

我尝试将脚本重命名为以电子邮件形式发送的日期(这是脚本的第一部分,但对此部分并不重要)然后重命名和排序它变成了一个完整的'夹。这就是我的代码看起来像

编辑 - 我把所有导入的东西放在顶部并且我没有显示它,但我认为我有正确的东西导入,如果你想看到只是问

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)

但我一直收到此错误

 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'

关于我做错什么的任何想法?

1 个答案:

答案 0 :(得分:2)

2个错误:

  1. 您不在当前目录

  2. 你不能在名字中加斜杠。文件系统不允许它(交替地)用于分隔路径部分。

  3. 首先,使用下划线直接生成日期:

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

    然后替换

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

    通过

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

    A Test.txt将在您指定的目录中重命名为21_9_2016 A Test.txt