pythonpathos.path

Python os.path.relpath behavior


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


Solution

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