簡體   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