HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Simplify Unix path

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pathsimplifyunix

Problem

Here is my code for simplifying a Unix path. Any advice is highly appreciated, including higher efficiency from an algorithm time complexity perspective, or any bugs.

'''
Simplify Unix path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
'''

def simplify_path(original_path):
    result = []
    levels = original_path.split('/')
    for level in levels:
        if level == '.':
            continue
        elif level == '..':
            result.pop(-1)
        else:
            result.append(level)

    result_str = '/'.join(result)
    return result_str[0:len(result_str)-1]

if __name__ == "__main__":
    print simplify_path('/a/./b/../../c/')
    print simplify_path('/home/')

Solution

There's definitely an easier way of doing this. You can use os.path.realpath() to get the canonical path.


os.path.realpath(path)

Return the canonical path of the specified
filename, eliminating any symbolic links encountered in the path (if
they are supported by the operating system).

Example:

from os.path import realpath

def simplify_path(original_path):
"""
Given an absolute path for a file, simplify it
"""
    return realpath(original_path)

if __name__ == '__main__':
    print(simplify_path('/a/./b/../../c/'))
    print(simplify_path('/home/'))


[dexter@localhost]$ python simplify_path.py 
/c
/home

Code Snippets

from os.path import realpath


def simplify_path(original_path):
"""
Given an absolute path for a file, simplify it
"""
    return realpath(original_path)

if __name__ == '__main__':
    print(simplify_path('/a/./b/../../c/'))
    print(simplify_path('/home/'))
[dexter@localhost]$ python simplify_path.py 
/c
/home

Context

StackExchange Code Review Q#149058, answer score: 5

Revisions (0)

No revisions yet.