Friday, July 13, 2012

Converting Relative Path to Absolute Path in Python

#!/usr/bin/env python

def get_absolute_path(path):
    files = path.split("/")
    l = []
    for f in files:
        if f == "..":
            l.pop()
        else:
            l.append(f)
    return "/".join(l)

if __name__ == "__main__":
    assert "/windows/temp/" == get_absolute_path("/windows/abs/../temp/new/../")
    assert "windows/temp/" == get_absolute_path("windows/abs/../temp/new/../")
    assert "/windows/temp" == get_absolute_path("/windows/abs/../temp/new/..")

1 comment:

  1. There's simpler and OS independent way:

    import os
    path = "../some_path"
    print os.path.abspath(path)

    ReplyDelete