pythonos.walk

os.walk is returning a generator object. What am I doing wrong?


According to the documentation, os.walk returns a tuple with root, dirs and files in a given path. When I call os.walk I get the following:

>>> import os

>>> os.listdir('.')
['Makefile', 'Pipfile', 'setup.py', '.gitignore', 'README.rst', '.git', 'Pipfile.lock', '.idea', 'src']

>>> root, dir, files = os.walk('src')

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)

>>> print (os.walk('src')) generator object walk at 0x10b4ca0f8>

I just don't understand what I'm doing wrong.


Solution

  • You can convert it to a list if that's what you want:

    list(os.walk('src'))
    

    There is a little more to what generators are used for (probably best to just google "Python Generators" and read about it), but you can still for-loop over them:

    for dirpath, dirnames, filenames in os.walk('src'):
        # Do stuff