2

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).

KLonge
  • 55
  • 7

1 Answers1

2

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.

DarQ
  • 92
  • 9
  • Thank you soooo much. I didn't realise it was renaming the folder names as well (should have been more careful). Would I be right in saying that if the folder names didn't have spaces then os.rename would have worked? Once again, thank you so so much. – KLonge Jan 07 '21 at 19:23
  • I think so yeah. I'm assuming it worked for you so I'm glad I helped. – DarQ Jan 07 '21 at 19:28