开发者

Formatting File Paths

开发者 https://www.devze.com 2023-03-19 15:50 出处:网络
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 di

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 spe开发者_运维技巧cified 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消