Question

I was using python 2.6 for a script, but for requirement limitations I have to downgrade my script to python 2.5, how can I get the relative path using python 2.5?

I was previously using:

os.path.relpath(path[, start])

But since this is new from 2.6 I can't use it anymore.

Thanks and regards!

Was it helpful?

Solution

Try Relative paths in Python it should have valuable information to you.

>>> import sys
>>> import os.path
>>> sys.path[0]
'C:\\Python25\\Lib\\idlelib'
>>> os.path.relpath(sys.path[0], "path_to_libs") # if you have python 2.6
>>> os.path.join(sys.path[0], "path_to_libs")
'C:\\Python25\\Lib\\idlelib\\path_to_libs'

EDIT: Found something more http://www.saltycrane.com/blog/2010/03/ospathrelpath-source-code-python-25/ It is a re-implementation by James Gardner:

from posixpath import curdir, sep, pardir, join

def relpath(path, start=curdir):
    """Return a relative version of a path"""
    if not path:
        raise ValueError("no path specified")
    start_list = posixpath.abspath(start).split(sep)
    path_list = posixpath.abspath(path).split(sep)
    # Work out how much of the filepath is shared by start and path.
    i = len(posixpath.commonprefix([start_list, path_list]))
    rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
    if not rel_list:
        return curdir
    return join(*rel_list)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top