0
#!/usr/bin/env python3.2
import os
import sys


fileList = []
rootdir = sys.argv[1]
for subdir, dirs, files in os.walk(rootdir, followlinks=True):
    for file in files:
            f = os.path.join(subdir,file)
            if os.path.islink(file):
                countlink = countlink+1
                linkto = os.readlink(f)
                print(linkto)

If i give this code a folder say /Current and files /Current/file.exe and a symlink /Current/link, the "islink" doesnt recognize the "link" symlink but considers it a directory and moves on to the actual file it links to. My requirement is to just stop when it finds a symlink and print it. i am using Python3.2

RashMans
  • 321
  • 1
  • 4
  • 17

1 Answers1

1

The problem seems to be that you're printing what readlink returns which is the name of the target. Additionally, you're printing every file in the middle loop. The True value for followLinks is causing you to recurse into directories that are symlinked. Lastly, any symlinks to directories are stored in dirs but not in files. The following should work:

for subdir, dirs, files in os.walk(rootdir, followlinks=False):
for file in files+dirs:
        f = os.path.join(subdir,file)
        if os.path.islink(file):
            countlink = countlink+1
            linkto = os.readlink(f)
            print("{} -> {}".format(f,linkto))
ABS
  • 2,092
  • 1
  • 13
  • 6
  • this doesnt resolve the issue, the problem is the code prints stuff inside the symlink and doesnt stop at the symlink. It considers the symlink to be a "dir" or "subdir" and recursing through the files doesnt help. How do i weed out everything other than the symlink? – RashMans Feb 23 '12 at 01:42
  • Do you want the code to break after the first symlink? Is the symlink to a file or directory? What OS are you using? – ABS Feb 23 '12 at 01:50
  • i dont want the code to break after the first symlink, but want it to print all the symlinks. For example if i have a directory current and have multiple files under /current and have multiple symlinks under /Current say link1, link2 link3 i want the code to ignore non symlinks and just print link1->actual target, link2->actual target etc – RashMans Feb 23 '12 at 01:56
  • See the edited answer above. The items in the symlinked directory were printed because followLinks was True and the symlinks weren't since directory symlinks are only in the dirs list. – ABS Feb 23 '12 at 02:21