开发者

Python os.walk + follow symlinks

开发者 https://www.devze.com 2023-01-17 08:29 出处:网络
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):

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消