我有一个目录bar
在一个目录foo
中,文件foo_file.txt
在目录foo
中,文件bar_file.txt
在目录bar
;即
computer$ ls
foo/
computer$ ls foo/
bar/ foo_file.txt
computer$ ls foo/bar/
bar_file.txt
使用pythonos.path.relpath函数,我希望:
os.path.relpath('foo/bar/bar_file.txt', 'foo/foo_file.txt')
给我:
'bar/bar_file.txt'
然而,它实际上给了我:
'../bar/bar_file.txt'
这是为什么?有没有一个简单的方法来达到我想要的行为?
编辑:这是在带有Python2.7.3的Linux上
os.path.relpath()
假设其参数是目录。将给出arg2在arg1目录中的相对路径。在您的情况下,为了从arg2到arg1,您需要cd up one directory(..),go the bar directory(bar),and the bar_file.txt。因此,相对路径是
relpath
有意外行为。它将路径的所有元素视为一个目录。所以,在这条路上:/path/to/a/file.txt
file.txt
也被视为一个目录。这意味着当您在两条路径上运行
relpath
时这是不正确的。从目录源到目标的真正相对路径是
'../dest/file.txt'
如果你试图创建符号链接,但最终它们的格式不正确,这会特别令人沮丧。
解决方案
要解决这个问题,我们必须首先找出路径是否指向一个文件,如果不是,我们可以像往常一样进行比较,否则我们需要从末尾删除文件名,只与目录进行比较,然后将文件添加回末尾。
注意,只有在系统上实际创建了这些文件时,这才有效,python必须访问文件系统才能找到节点类型。
要获取从目录源到目标的实际相对路径,请运行:
我颠倒了参数顺序,因为在我的大脑中,更合理的说法是,“我想知道从arg1到arg2的相对路径”,标准的
relpath
实现是向后的(可能是因为UNIX就是这样做的)。这种访问文件系统的需要是
relpath
具有如此奇怪行为的真正原因。文件系统调用很昂贵,所以python让您知道您是在处理文件还是在处理目录,并且只在您提供的路径上执行字符串操作。注意:可能有一种方法可以使
realrelpath
函数更有效率。例如,我不确定是否需要abspath
调用,或者是否可以通过返回更多信息的syscall与os.path.isfile
检查绑定。我欢迎改进。相关问题 更多 >
编程相关推荐