Reputation: 23
What I have is a path of a file which is in the home directory, and I wish to process it to become shorten path which includes "~" in it.
For example, my input could be:
"/home/username/test"
or /home/./username/test
or /home/../home/username/test
and I wish to get
~/test
I tried to .split("/")
and match the first 2 terms, but when it's a little more complicated with all those "." and ".." I have no idea how to achieve this.
How do I process paths in an efficient way to achieve the above goal?
Upvotes: 0
Views: 202
Reputation: 23
Thanks for all the help!
My final solution using os.path.realpath()
is as follow
Please comment if I have done something wrong or if there is a better way!
from os import path
def getShortPath(p):
realpath = path.realpath(p).split("/")[1:]
homepath = path.expanduser("~").split("/")[1:]
if realpath[:2] == homepath:
processed = "~"
realpath = realpath[2:]
else: processed = "/"
for i in realpath:
processed = path.join(processed,i)
return processed
Upvotes: 0
Reputation: 1395
Use os.path.realpath to convert a path to canonical form and then check if the beginning is the same as a home directory.
Upvotes: 2