28

如何获得这篇文章,以遵循Python 2.6中的符号链接?Python os.walk +关注符号链接

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 

回答

42

设置followlinksTrue。这是第四个参数os.walk方法,以下再现:在Python 2.6的溶液中加入

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

此选项。

+5

谢谢'os.walk(path,followlinks = True):'做了窍门,尽管Python文档对此很不明确:http://docs.python.org/library/os.path.html# os.path.walk – 2010-09-22 17:08:04

+6

@Frank:当然不清楚;你正在查看'os.path.walk'的文档,它是一个单独的(旧的和不赞成的)函数。您应该查看['os.walk'](http://docs.python.org/library/os.html#os.walk)文档。 – tzot 2010-10-22 10:14:21