格式化文件路径 [英] Formatting File Paths

查看:167
本文介绍了格式化文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,所以我可能会做这个完全错误的,但是我遇到问题并且改变到一个文件的目录。我的脚本需要多个文件名,可以在任何目录。在我的脚本中,我需要python改变到文件的目录,然后执行一些操作。但是,我在更改目录时遇到了问题。



以下是我到目前为止所尝试的内容:

<$ p
os.chdir(path [0])
<执行路径指定的文件路径[code> path = os.path.split(<文件路径> 1] GT;

获取文件路径的方式是从资源管理器拖到命令行。这就像C:\foo\bar\file_name.txt一样输入路径名。当我在解释器中运行第一行时,我得到了('C:\\\\\\\\'','file_name.txt')。问题是,由于某种原因,最后一个反斜杠不会自动转义,所以当我运行 os.chdir(path [0])时,我得到错误。



我的问题是为什么最后一个反斜杠不能像其他的一样自动转义?我如何手动转义最后一个反斜杠?有没有更好的方法来获取文件的目录,并改变它?

解决方案

最后一个反斜杠不会自动转义当下面的字符没有用反斜杠形成转义序列时,Python只能在常规字符串中转义反斜杠。事实上,在你的例子中,你不会得到'C:\ foo \\ \\ bar',你会得到'C:\x0coo\x08ar'



你想要做的是用正斜杠来替换反斜杠,或者为了简化拖放操作,只需在 r 之前加上路径即可这是一个原始的字符串,不能识别转义序列。

 >>> os.path.split(rC:\foo\bar\file_name.txt)
('C:\\\\\'','file_name.txt')


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')

这篇关于格式化文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆