Python os.path.relpath行为 [英] Python os.path.relpath behavior
本文介绍了Python os.path.relpath行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在目录foo
中有一个目录bar
,目录foo
中有文件foo_file.txt
,目录bar
中有文件bar_file.txt
;即
I have a directory bar
inside a directory foo
, with file foo_file.txt
in directory foo
and file bar_file.txt
in directory bar
; i.e.
computer$ ls
foo/
computer$ ls foo/
bar/ foo_file.txt
computer$ ls foo/bar/
bar_file.txt
使用python os.path.relpath 函数,我希望:
Using the python os.path.relpath function, I expect:
os.path.relpath('foo/bar/bar_file.txt', 'foo/foo_file.txt')
给我:
'bar/bar_file.txt'
但是,它实际上给了我
'../bar/bar_file.txt'
这是为什么?是否有一种简单的方法来获得我想要的行为?
Why is this? Is there an easy way to get the behavior I want?
这是在具有Python 2.7.3的Linux上
This is on Linux with Python 2.7.3
推荐答案
os.path.relpath()
假定其参数为目录.
>>> os.path.join(os.path.relpath(os.path.dirname('foo/bar/bar_file.txt'),
os.path.dirname('foo/foo_file.txt')),
os.path.basename('foo/bar/bar_file.txt'))
'bar/bar_file.txt'
这篇关于Python os.path.relpath行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文