39

How do I get this piece to follow symlinks in python 2.6?

def load_recursive(self, path):
    for subdir, dirs, files in os.walk(path):
        for file in files:
            if file.endswith('.xml'):
                file_path = os.path.join(subdir, file)
                try:
                    do_stuff(file_path) 
                except:
                    continue
fmalina
  • 6,120
  • 4
  • 37
  • 47

1 Answers1

64

Set followlinks to True. This is the fourth argument to the os.walk method, reproduced below:

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

This option was added in Python 2.6.

EDIT 1

Be careful when using followlinks=True. According to the documentation:

Note: Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already.

rmmariano
  • 896
  • 1
  • 18
  • 32
Richard Cook
  • 32,523
  • 5
  • 46
  • 71
  • 8
    Thank you, `os.walk(path, followlinks=True):` did the trick, although Python documentation was quite unclear about this: http://docs.python.org/library/os.path.html#os.path.walk – fmalina Sep 22 '10 at 17:08
  • 8
    @Frank: of course it was unclear; you're looking at the documentation for `os.path.walk` which is a separate (older and deprecated) function. You should be looking at the [`os.walk`](http://docs.python.org/library/os.html#os.walk) documentation. – tzot Oct 22 '10 at 10:14