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.
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.
os. walk() creates a generator that produces a directory's subdirectories and their files.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With