Formatting File Paths

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?

+5
source share
2 answers

The last backslash is not automatically escaped because Python avoids backslashes in regular lines when the next character does not form a backslash escape sequence. In fact, in your example, you would not receive 'C:\\foo\bar'from 'C:\foo\bar', you would receive 'C:\x0coo\x08ar'.

, , forwardslhes, , r, escape .

>>> os.path.split(r"C:\foo\bar\file_name.txt")
('C:\\foo\\bar','file_name.txt')
+5

. , , :

path=os.path.split(r'C:\foo\bar\file_name.txt')

r , Python escape-.

+2

All Articles