I'm new to Python so I may be going about this completely wrong, but I'm having problems getting and changing to the directory of a file. My script takes in multiple file names that can be in any directory. In my script I need python to change to the directory of the file and then perform some actions. However, I'm having problems changing directories.
Here is what I've tried so far:
path=os.path.split(<file path>)
os.chdir(path[0])
<Do things to file specified by path[1]>
The way I've been getting the file path is by dragging from explorer to the command line. This enters the path name as something like "C:\foo\bar\file_name.txt"
. When I run the first line in the interpreter I get out ('C:\\foo\bar','file_name.txt')
. The problem is that for some reason the last backslash isn't automatically escaped so when I run the os.chdir(path[0])
line I get errors.
My question is why is the last backslash not being automatically escaped like the others? How can I manually escape the last backslash? Is there a better way to get the file's directory and change to it?
The last backslash isn't being automatically escaped because Python only escapes backslashes in regular strings when the following character does not form an escape sequence with the backslash. In fact, in your example, you would NOT get 'C:\\foo\bar'
from 'C:\foo\bar'
, you'd get 'C:\x0coo\x08ar'
.
What you want to do is either replace the backslashes with forwardslashes, or to make it simpler for drag-and-drop operations, just prepend the path with r
so that it's a raw string and doesn't recognize the escape sequences.
>>> os.path.split(r"C:\foo\bar\file_name.txt")
('C:\\foo\\bar','file_name.txt')
You're using the right modules and methods. Just when you're putting that windows path in there, make the string a raw string, so your command should look like:
path=os.path.split(r'C:\foo\bar\file_name.txt')
Note the r
in front of the first quote, that makes Python not treat the backslashes in the string as escape sequences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With