繁体   English   中英

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

[英]os.rename Error “The system cannot find the path specified”

已经在 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 文件位于同一个文件夹中(尽管我认为这不会有所不同)。

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

暂无
暂无

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

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