dusktreader
dusktreader

Reputation: 4055

How can I expand a relative path without expanding symlinks?

I have a path like:

/home/me/work/project/a/b/c

Which, is actually uses an awful symlink like:

/home/me/work -> /mnt/device/volume/storage/work/me/

I'm using git to show the top-level of the git clone which is:

/home/me/work/project

If I use:

$ git rev-parse --show-toplevel
/mnt/device/volume/storage/work/me/project

I get the full expanded absolute path. I don't want that. So, I can use:

$ git rev-parse --show-cdup
../../..

to get the relative path to the top

Now, I would just love it if I could figue out how to get python to expand that relative path to:

/home/me/work/project

instead of:

/mnt/device/volume/storage/work/me/project

Is this possible?

Upvotes: 1

Views: 1319

Answers (1)

unutbu
unutbu

Reputation: 880479

How about:

>>> import os
>>> os.path.normpath(os.path.join(os.environ['PWD'], '../../..'))
'/home/me/work/project'

os.path.normpath doesn't follow symlinks; it does not even care if the file system exists. It simply computes what the normalized path would be after eliminating double slashes and double dots.

Upvotes: 2

Related Questions