Somu
Somu

Reputation: 15

Traversing multiple symbolic links recursively in Python

I want to write a recursive function to traverse symbolic links from source path to destination path

Example: 1)readlink patha/pathb/pathc -> gives if symbolic link exists 2)readlink patha/pathb/pathc/ -> gives if symbolic link exists

I'm using os.readlink method in python to get symbolic link in Python but how to traverse multiple symbolic links

Reason for traverse: If its in future someone wants to add file3 symbolic link in between , then I wanted a recursive function to traverse each symbolic links and gives the final dest path
file1 -> file2 -> .... -> for getting destination path

Upvotes: 1

Views: 832

Answers (1)

Epic Chen
Epic Chen

Reputation: 1382

You could simply use

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

Upvotes: 0

Related Questions