Python os.walk + follow symlinks

24,362

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.

Share:
24,362
fmalina
Author by

fmalina

Python programming contractor writing Python for over 14 years. Consulting, training and up-skilling teams and individual developers. Development of new systems in trading, banking, e-commerce, knowledge organisation, real estate and gas/power control sectors. Support for existing Python applications, specialist in refactoring and upgrades to latest Python and latest Linux, maintenance contracts of business critical Python based applications and repayment of technical debt using de-duplication, full-stack code cleaning (Python, HTML, CSS, JS, SQL, configs), streamlining for performance, automated testing, well written and code generated documentation and continuous integration with static code analysis. Focused on delivering quality work and value to customer. Contract rates starting from £600 per day via UK limited company, maintenance subscription contracts negotiable. Author of Unilexicon taxonomy editor Unilexicon API for medicines Transcript PDF to semantic HTML

Updated on May 22, 2021

Comments

  • fmalina
    fmalina almost 3 years

    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
    fmalina over 13 years
    Thank you, os.walk(path, followlinks=True): did the trick, although Python documentation was quite unclear about this: docs.python.org/library/os.path.html#os.path.walk
  • Ishbir
    Ishbir over 13 years
    @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 documentation.