问题
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.
回答1:
os.path.realpath(path)
os.path.realpath returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path.
回答2:
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.
回答3:
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')
)
)
回答4:
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.
回答5:
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)
.
回答6:
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.
来源:https://stackoverflow.com/questions/3220755/how-to-find-the-target-files-fullabsolute-path-of-the-symbolic-link-or-soft-l