Frankium
Frankium

Reputation: 23

Python3 - Shorten path for home directory in Ubuntu

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

Answers (3)

Frankium
Frankium

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

szatkus
szatkus

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

AlexKh
AlexKh

Reputation: 546

Try to use

from pathlib import Path
home_path = str(Path.home())

Here is the documentation link

Upvotes: 0

Related Questions