John Bielowski
John Bielowski

Reputation: 309

How to find all symlinks in directory and its subdirectories in python

I need to list symlinks using python. Broken aswell

How do I do it? I was searching everywhere and tried alot.

The best result I found was:

import os,sys
print '\n'.join([os.path.join(sys.argv[1],i) 
    for i in os.listdir(sys.argv[1]) if 
    os.path.islink(os.path.join(sys.argv[1],i))])

It does not show where its linked to and it doesn't go to subdirs.

Upvotes: 2

Views: 3307

Answers (1)

Geeshan
Geeshan

Reputation: 534

You can use a code similar to this one to achieve what you need. Directories to search are passed as arguments or current directory taken as the default. You can modify this further with the os.walk method to make it recursive.

import sys, os

def lll(dirname):
    for name in os.listdir(dirname):
        if name not in (os.curdir, os.pardir):
            full = os.path.join(dirname, name)
            if os.path.isdir(full) and not os.path.islink(full):
                lll(full)
            elif os.path.islink(full):
                print(name, '->', os.readlink(full))
def main(args):
    if not args: args = [os.curdir]
    first = 1
    for arg in args:
        if len(args) > 1:
            if not first: print()
            first = 0
            print(arg + ':')
        lll(arg)

if __name__ == '__main__':
    main(sys.argv[1:])

Ref: https://github.com/python/cpython/blob/master/Tools/scripts/lll.py

Upvotes: 2

Related Questions