Search code examples
pythonstringvariablesoperating-system

Problems with os.rename | OSError: [WinError 123]


I'm looking to rename one of my files using os.rename, the code is a little bit messy but currently it gives me a result that looks like it should work, but I end up getting an error. (path is removed but it is not actually removed in the code)

Snippet of my code:

mxk='''"'''
root = Tk()
root.withdraw()
m = root.clipboard_get() #all clipboard functions working 
bb=r"\blank.pdf"
cc=mxk
nd = (m[:40]+bb+cc)
print(m,nd)
os.rename(m, nd)

Print response: (m, nd)

"C:\l-final_words.pdf" "C:\blank.pdf"

Error:

 File "C:\main.py", line 179, in <module>
    os.rename(m, nd)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '"C:\\l-final_words.pdf"' -> '"C:\\Ublank.pdf"'

Does anybody have any suggestions fixing this code?


Solution

  • You shouldn't have explicit quotes around the filenames.

    Also, use os.path functions to merge a filename with the directory of the original file, rather than string slicing with a magic number.

    root = Tk()
    root.withdraw()
    m = root.clipboard_get().strip('"') #all clipboard functions working 
    bb=r"blank.pdf"
    nd = os.path.join(os.path.dirname(m), bb)
    print(m,nd)
    os.rename(m, nd)