9

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.

Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
SpaDev
  • 149
  • 2
  • 7

2 Answers2

11

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
Stephen C
  • 1,966
  • 1
  • 16
  • 30
0

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.

  • 1
    How does this improve the accepted answer? – doneforaiur Jul 07 '23 at 08:59
  • 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](/help/how-to-answer). – Community Jul 09 '23 at 17:00