-->

Python os.path.relpath behavior

2019-03-16 06:46发布

问题:

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

Using the python os.path.relpath function, I expect:

os.path.relpath('foo/bar/bar_file.txt', 'foo/foo_file.txt')

to give me:

'bar/bar_file.txt'

However, it actually gives me:

'../bar/bar_file.txt'

Why is this? Is there an easy way to get the behavior I want?

EDIT: This is on Linux with Python 2.7.3

回答1:

os.path.relpath() assumes that its arguments are directories.

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


回答2:

os.path.relpath(arg1, arg2) 

will give the relative path of arg2 from the directory of arg1. In order to get from arg2 to arg1 in your case, you would need to cd up one directory(..), go the bar directory(bar), and then the bar_file.txt. Therefore, the relative path is

../bar/bar_file.txt