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

醉酒当歌 提交于 2019-11-28 21:00:27
os.path.realpath(path)

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

Dave Burton

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.

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.

Update:

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') 
  ) 
)

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).

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.

Alex

I recommend to use 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!