Search code examples
outputos.walkempty-listpython-os

What are the return values of os.walk() in python?


I have a directory structure like this:

dir/
└── subdir

My code:

import os

for d in os.walk('dir'):
    print(d)

I get the output:

('dir', ['subdir'], [])
('dir/subdir', [], [])

My question is what are those trailing [ ]s ?

There is 1 in the first tuple and 2 in the second.. it confuses me.


Solution

  • It's worth checking out the Python docs for questions like this as they tend to have pretty solid documentation: https://docs.python.org/2/library/os.html#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).

    So it will always return a 3-tuple.

    For your first directory 'dir', it contains one directory called 'subdir', and it doesn't contain any files so there's an empty list for filenames.

    It then has another entry for subdir, which is your 'dir/subdir'. 'subdir' doesn't have any directories or files under it, so you have empty lists for both dirnames and filenames. The key thing is that it always returns a 3-tuple, and the last two elements are always lists, so there are no subdirectories or files, it will return empty lists.