如何在 Python 中访问 symlink 的 link 文本?

How do I access in Python the link text of a symlink?

对于 Python 中的文件系统比较工具,我想找出符号 link 的 link 文本是什么。我不想遵循 link,而是找到 link 文本以及它是绝对的还是相对的。

示例:对于通过 ls -l 打印

的 link
lrwxr-xr-x  1 tutor  staff    16B 25 Aug 17:13 etc -> dir-with-dir/etc

我想以这种相对形式准确检索文本 "dir-with-dir/etc"。

如何在 Python 中访问此信息?

您可以使用 os.readlink(path) 找到符号 link 的 linked 文件。来自 documentation:

Return a string representing the path to which the symbolic link points.

另请查看相关 SO 问题中更详细的答案: