Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting File Paths

Tags:

python

file-io

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?

like image 486
rhololkeolke Avatar asked Jul 11 '11 15:07

rhololkeolke


2 Answers

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')
like image 182
JAB Avatar answered Oct 02 '22 14:10

JAB


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.

like image 23
John Gaines Jr. Avatar answered Oct 02 '22 16:10

John Gaines Jr.