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

2

10

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.

Refusal answered 9/12, 2018 at 15:33 Comment(1)
Code formatting and grammar tweaksAllin
W
14

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
Wardwarde answered 9/12, 2018 at 15:36 Comment(0)
R
1

Here's what I did and it worked:

x = os.walk('/home')
for b in x:
    print(b)

This should give you the path names.

Reefer answered 7/7, 2023 at 8:57 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Dehydrate

© 2022 - 2024 — McMap. All rights reserved.