Search code examples
pythonwindowspathname

Python on Windows 10: os.rename() cannot find a file that os.path.exists() finds?


I'm wondering about os.rename(): Even though os.path.exists() says the file exists, os.rename() says it cannot find it. Here's the code snippet:

        try:
            if (os.path.exists(sourcePath)):
                print('Safe: %s does exist!' % sourcePath)
            os.rename (sourcePath, newPath)
        except Exception as e:
            print('Error renaming "%s":' % sourcePath)
            raise e

Running this on a file named Y:\home\Paul\PaulsBilder\images\..\import\batch0\2012-05 Neuruppin\12-05 - 0 2.JPG yielded the following output:

Safe: Y:\home\Paul\PaulsBilder\images\..\import\batch0\2012-05  Neuruppin\12-05 - 0 2.JPG does exist!
Error renaming "Y:\home\Paul\PaulsBilder\images\..\import\batch0\2012-05  Neuruppin\12-05 - 0 2.JPG":
Traceback (most recent call last):
 :
WindowsError: [Error 3] Das System kann den angegebenen Pfad nicht finden

(German Windows: "The system cannot find the specified path.") I've been using this snippet some time now without issues, but probably never on filenames with spaces... But then, when I replace the spaces with underscores, the filename still can't be found.

Something else must be wrong, but what?

EDIT: Removing the /../ component (by wrapping os.normpath() around it) does not help.


Solution

  • Thanks a lot, Skycc, you're perfectly right: The error occurred because the directory of the new pathname did not exist. Silly me.

    This one works - make sure os.makedirs() is only called once:

            try:
                if (os.path.exists(sourcePath)):
                    print('Safe: %s does exist!' % sourcePath)
                (head, tail) = os.path.split(newPath)  # @UnusedVariable
                if (not os.path.exists(head)):
                    os.makedirs(head)
                os.rename(sourcePath, newPath)
            except Exception as e:
                print('Error renaming "%s" to "%s":' % (sourcePath, newPath))
                raise e