Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

os.walk

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.

like image 308
SpaDev Avatar asked Dec 09 '18 15:12

SpaDev


People also ask

What does OS walk return in Python?

os. walk() returns a list of three items. It contains the name of the root directory, a list of the names of the subdirectories, and a list of the filenames in the current directory.

Is OS walk a generator?

os. walk() creates a generator that produces a directory's subdirectories and their files.

What is the difference between OS Listdir () and OS walk?

The Python os. listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.

What does it mean to walk a directory?

The walk function generates the file names in a directory tree by navigating the tree in both directions, either a top-down or a bottom-up transverse. Every directory in any tree of a system has a base directory at its back. And then it acts as a subdirectory.


1 Answers

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, dirname, filename in os.walk('src'):
    # Do stuff
like image 61
Stephen C Avatar answered Sep 22 '22 15:09

Stephen C