Python os.walk + follow symlinks

fmalina picture fmalina · Sep 22, 2010 · Viewed 21.1k times · Source

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

Answer

Richard Cook picture Richard Cook · Sep 22, 2010

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.