Simplify the directory path in Python
In this post, we will learn how to simplify a directory path from absolute to canonical using the Python Programming language.
The absolute path is used in UNIX/bash which needs to be simplified to its canonical path in order to work with further tasks thereby increasing portability of a program.
What is Canonical path?
A Canonical path is defined as the shortest string representing the absolute path which is unique, it cleans up the absolute path by resolving stuff like ., .. , successive /.
Properties of a canonical path:-
- The path must always begin with a /
- Consecutive / between two directory names are not allowed
- Last directory name should not end with /
As we can see that the operations perform well when we consider this as a stack. Whenever we encounter a directory we push it onto the stack, if we encounter a period .., we pop the previous directory element else, we continue.
- Let us consider a list st and put ‘/‘ onto it.
- The test is the list of strings after splitting the path with the delimiter provided.
- Looping for all the elements in the test
- if i is .. then,
- if st>1 then, pop from st, else continue
- else if i is . , then continue
- else if it is not an empty string hence concatenate i with / and store into st
- if i is .. then,
- if only one element, return /
- return after concatenating all elements present in st
class soln: def SimplifyPath(self,test): st = ['/'] test = test.split("/") for i in test: if i == "..": if len(test)>1: test.pop() else: continue elif (i == '.'): continue elif i != '': st.append("/" + str(i)) if len(st)==1: return "/" return "".join(st[1:]) ob=soln() print(ob.SimplifyPath("/home/"))
Input : /home/ Output : /home Input : /a/./b/../../c/ Output : /c Input : /a/.. Output:/ Input : /a/../ Output : / Input : /../../../../../a Output : /a Input : /a/./b/./c/./d/ Output : /a/b/c/d Input : /a/../.././../../. Output:/ Input : /a//b//c//////d Output : /a/b/c/d