Search code examples
python-2.7replacefilenames

WindowsError:[Error 123] When Replace in filename "%3" by ":"


I am running this script:

import os

for filename in os.listdir("."):
    newname = filename.replace("%3",":")
    if newname != filename:
        os.rename(filename,newname)

which throws:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

Any idea why this happens?

thanks in advance


Solution

  • Windows files cannot contain the ':' character: (or any of \ / : * ? " < > | as they are reserved characters.)

    Try:

    import os
    
    for filename in os.listdir("."):
        newname = filename.replace("%3","-")
        if newname != filename:
            os.rename(filename,newname)