os.rename 错误“系统找不到指定的路径”

时间:2021-01-07 18:52:39

标签: python batch-rename

已经在 SO 上提出了类似的问题,实际上我是从这里的帖子中得到的代码,但是我在调​​试这个错误时遇到了麻烦。

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk(r'C:\Users\kevin\Diamond Line JPEGS\Diamond Line JPEGS')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace(' ', '_')
    if newname != path:
        print(path)
        print(newname)
        os.rename(path, newname)

当我使用 os.rename(path,path) 时,它可以工作,所以我知道问题一定出在 newname 上,而且很可能是我对 os.rename 的工作原理缺乏了解。它不相信 newname 存在,因为以下错误突出显示:

[WinError 3] The system cannot find the path specified: 'C:\\Users\\kevin\\Diamond Line JPEGS\\Diamond Line JPEGS\\Test 01.jpg' -> 'C:\\Users\\kevin\\Diamond_Line_JPEGS\\Diamond_Line_JPEGS\\Test_01.jpg'

我不认为新目录名称需要“存在”才能重命名它,所以我很困惑。我已经阅读了文档,但我仍然不明白为什么它会失败。我正在使用的 Python 文件在同一个文件夹中(尽管我认为这不会在这里产生影响)。

1 个答案:

答案 0 :(得分:0)

使用 os.renames 而不是 os.rename。问题是 os.rename 只更改最上层目录的名称,因此在您的情况下,它会在不存在的“C:\Users\kevin\Diamond_Line_JPEGS\Diamond_Line_JPEGS\”中查找“Test 01.jpg”。