duhhunjonn
duhhunjonn

Reputation: 45535

how to find the target file's full(absolute path) of the symbolic link or soft link in python

when i give ls -l /etc/fonts/conf.d/70-yes-bitmaps.conf

lrwxrwxrwx <snip> /etc/fonts/conf.d/70-yes-bitmaps.conf -> ../conf.avail/70-yes-bitmaps.conf

so for a symbolic link or soft link, how to find the target file's full(absolute path) in python,

If i use

os.readlink('/etc/fonts/conf.d/70-yes-bitmaps.conf')

it outputs

../conf.avail/70-yes-bitmaps.conf

but i need the absolute path not the relative path, so my desired output must be,

/etc/fonts/conf.avail/70-yes-bitmaps.conf

how to replace the .. with the actual full path of the parent directory of the symbolic link or soft link file.

Upvotes: 87

Views: 88296

Answers (6)

eruciform
eruciform

Reputation: 7726

http://docs.python.org/library/os.path.html#os.path.abspath

also joinpath() and normpath(), depending on whether you're in the current working directory, or you're working with things elsewhere. normpath() might be more direct for you.

Specifically:

os.path.normpath( 
  os.path.join( 
    os.path.dirname( '/etc/fonts/conf.d/70-yes-bitmaps.conf' ), 
    os.readlink('/etc/fonts/conf.d/70-yes-bitmaps.conf') 
  ) 
)

Upvotes: 12

Alex
Alex

Reputation: 1375

I recommend using pathlib library for filesystem operations.

import pathlib

x = pathlib.Path('lol/lol/path')
x.resolve()

Documentation for Path.resolve(strict=False): make the path absolute, resolving any symlinks. A new path object is returned.

Upvotes: 12

Dave Burton
Dave Burton

Reputation: 3040

As unutbu says, os.path.realpath(path) should be the right answer, returning the canonical path of the specified filename, resolving any symbolic links to their targets. But it's broken under Windows.

I've created a patch for Python 3.2 to fix this bug, and uploaded it to:

http://bugs.python.org/issue9949

It fixes the realpath() function in Python32\Lib\ntpath.py

I've also put it on my server, here:

http://www.burtonsys.com/ntpath_fix_issue9949.zip

Unfortunately, the bug is present in Python 2.x, too, and I know of no fix for it there.

Upvotes: 18

alpha_989
alpha_989

Reputation: 5350

On windows 10, python 3.5, os.readlink("C:\\Users\PP") where "C:\Users\PP" is a symbolic link (not a junction link) works.

It returns the absolute path to the directory.

This works on Ubuntu 16.04, python 3.5 as well.

Upvotes: 1

Don Kirkby
Don Kirkby

Reputation: 56590

The documentation says to use os.path.join():

The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using os.path.join(os.path.dirname(path), result).

Upvotes: 0

unutbu
unutbu

Reputation: 879093

os.path.realpath(path)

os.path.realpath returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path.

Upvotes: 156

Related Questions