On a Windows machine I am trying to write a scrip which would change the Python (I am using Anaconda Spyder 5.4) working directory to the directory of some files I am trying to feed to the script.
The path to the target folder is very long, probably more than 10 directories nested and I might need to change the path for subsequent operations, so doing it by hand would not be appropriate.
Hence, I would like to write a Python script which prompts the user for the path and then the user pasted the path he copied from Windows explorer.
For exemplification:
Windows Explorer path is: D:\Program\Anaconda\conda-meta
The problem is that Python treats some letters followed by backs lashes as special characters, so the string I read from the pasted Windows Explorer path is not valid.
I know that by replacing the back slashes with forward slashes would solve the issue, but manually doing that every time kind of defeats the point of programming.
I think a similar question has been asked here:
But I found no answer to my problem.
Thank you very much!
One way which works is reading the raw string as following:
import os
WinPath = r'D:\Program\Anaconda\conda-meta'
NewPath = os.fsencode(WinPath)
os.chandir(NewPath)
But this requires me writing the Windows Explorer path in the script, which I don't want. What I want is for the user to be asked to input the path by pasting. Something like:
import os
WinPath = input("Paste file path here:")
#somehow make it a raw string and encode it into the NewPath variable
os.chandir(NewPath)
But I have no idea how to actually do that.
I tried using the repr() function, but then I get an error saying the path is too long:
import os
WinPath = input("Paste file path here:")
WinPath = repr(WinPath)
NewPath = os.fsencode(WinPath)
os.chandir(NewPath)
Edit: @Matthias correctly indicated that the code should work fine, granted the os.chdir() function is properly called, which I tried right now on my personal PC and works.
Seems I don't properly understand the difference between input() and declaring a variable in the interpreter - I have tried to declare the WinPath in the interpreter as a test before writing the script and never actually made it to that step.
I guess the question can be closed.
Thank you very much for your support!