Skip to main content

Resolve the absolute paths of symlinks in the specified directory.

#!/usr/bin/env python

import os
import os.path


def find_symlinks(topdir):
    """Resolve the absolute file paths of symlinks.

    :type topdir: str The target directory
    :return: A key/val dict of symlinks and the the path to which
        the symbolic link points.
    :rtype: dict
    """
    from collections import defaultdict
    symlinks = defaultdict(list)
    for base_path, dirs, files in os.walk(topdir):
        for filename in files:
            filepath = os.path.join(base_path, filename)
            if os.path.islink(filepath):
                target = os.readlink(filepath)
                symlinks[os.path.basename(target)].append(filepath)
    return symlinks