首页 > 解决方案 > 在 Python 中递归遍历多个符号链接

问题描述

我想编写一个递归函数来遍历从源路径到目标路径的符号链接

示例:1)readlink patha/pathb/pathc -> 如果符号链接存在则给出 2)readlink patha/pathb/pathc/ -> 如果符号链接存在则给出

我在 python 中使用 os.readlink 方法来获取 Python 中的符号链接,但是如何遍历多个符号链接

遍历的原因:如果将来有人想在两者之间添加 file3 符号链接,那么我想要一个递归函数来遍历每个符号链接并给出最终的目标路径
file1 -> file2 -> .... -> 以获得目的地小路

标签: pythonpython-3.xrecursionsymlink-traversalreadlink

解决方案


你可以简单地使用

import os

def find_link(path):
   try:
        link = os.readlink(path)
        return find_link(link)
   except OSError: # if the last is not symbolic file will throw OSError
        return path

print(find_link("a/b/c"))

推荐阅读