Search code examples
pythonbatch-rename

os.rename Error "The system cannot find the path specified"


Similar questions have been asked about this on SO already, and I actually got this code from a post on here, but I am having trouble debugging this error.

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)

When I use os.rename(path,path), it works, so I know the problem must be with newname, and most likely my lack of understanding as to how os.rename works. It doesn't believe that newname exists as highlighted by the following error:

[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'

I didn't think the new directory name needed to "exist" in order for you to rename it, so I am quite confused. I have read the documentation, and I still don't understand why it is failing. The Python file I am using is in the same folder (although I don't imagine that should make a difference here).


Solution

  • use os.renames instead of os.rename. the problem is that os.rename only changes the name of the uppermost directory so in your case it looks for "Test 01.jpg" inside "C:\Users\kevin\Diamond_Line_JPEGS\Diamond_Line_JPEGS\" which doesn't exist.