-1

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?

10
  • Why are you appending literal double-quote characters to the filename? Get rid of the mxk stuff.
    – Barmar
    Commented Jul 5 at 15:30
  • It also looks like you're copying the double-quote characters into the clipboard. Don't do that.
    – Barmar
    Commented Jul 5 at 15:32
  • 1
    Quotes are needed when you're typing some filenames into the command prompt. They're not used when calling an API.
    – Barmar
    Commented Jul 5 at 15:32
  • The reason I'm adding a double quote at the end is because if I don't the print response will be missing an end quote and not be a valid path
    – Idokoond K
    Commented Jul 5 at 15:53
  • Paths don't need quotes to be valid. You're confusing the path with the shell syntax.
    – Barmar
    Commented Jul 5 at 15:54

1 Answer 1

0

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)

Not the answer you're looking for? Browse other questions tagged or ask your own question.