Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 486
duhhunjonn Avatar asked Jul 10 '10 20:07

duhhunjonn


People also ask

How do I find a symbolic link in Python?

path. islink() method in Python is used to check whether the given path represents an existing directory entry that is a symbolic link or not. Note: If symbolic links are not supported by the Python runtime then os.

Is soft link and symbolic link same?

A soft link (also known as Symbolic link) acts as a pointer or a reference to the file name. It does not access the data available in the original file. If the earlier file is deleted, the soft link will be pointing to a file that does not exist anymore. take the same inode number.

How do I create a symbolic link in target?

To create a symbolic link in Linux, we use the ln command. Executing the command with no options creates a hard link to the specified target file.


2 Answers

os.path.realpath(path) 

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

like image 119
unutbu Avatar answered Sep 21 '22 15:09

unutbu


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.

like image 34
Dave Burton Avatar answered Sep 20 '22 15:09

Dave Burton