Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os.walk + follow symlinks

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 
like image 227
fmalina Avatar asked Sep 22 '10 16:09

fmalina


People also ask

What does Python os walk return?

os. walk() returns a list of three items. It contains the name of the root directory, a list of the names of the subdirectories, and a list of the filenames in the current directory.

What is Dirpath in Python?

The dirpath is a string for the path to the directory. The dirnames is a list of the names of the subdirectories in dirpath (excluding '. ' and '..'). The filenames is a list of the names of the non-directory files in dirpath.

How does OS Walk () work in Python?

walk() work in python ? OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Can Python read symbolic links?

Description. Python method readlink() returns a string representing the path to which the symbolic link points. It may return an absolute or relative pathname.


1 Answers

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.

like image 139
Richard Cook Avatar answered Sep 23 '22 17:09

Richard Cook