I'm new to Python, so maybe I'm wrong, but I'm having trouble getting and moving to a file directory. My script accepts several file names that can be in any directory. In my script, I need python to switch to the file directory and then perform some actions. However, I am having problems changing directories.
Here is what I have tried so far:
path=os.path.split(<file path>)
os.chdir(path[0])
<Do things to file specified by path[1]>
The way I get the file path is dragged from Explorer to the command line. This introduces the path name as something of a sort "C:\foo\bar\file_name.txt". When I run the first line in the interpreter, I exit ('C:\\foo\bar','file_name.txt'). The problem is that for some reason the last backslash is not automatically escaped, so when I run the line os.chdir(path[0]), I get errors.
My question is: why doesn't the last backslash automatically disappear like the others? How can I manually avoid the last backslash? Is there a better way to get the file directory and change it?
source
share