dogsled
dogsled

Reputation: 1

Error on os.walk – I need the result for the specified directory only

Here is a demo what works for me and what doesn't:

import os
path2   = 'D:\\'

# this works
for curdir, dirlist, flist in os.walk(path2):
    pass

# this fails
curdir, dirlist, flist = os.walk(path2)

Upvotes: 0

Views: 682

Answers (2)

vallentin
vallentin

Reputation: 26245

The thing is that os.walk() returns a generator. So doing:

curdir, dirlist, flist = os.walk(path2)

Might or might not work.

First let's consider this:

for curdir, dirlist, flist in os.walk(path2):
    pass

This is essentially the same as assigning the generator returned by os.walk() to a name and continuously calling next() on that until a StopIteration is raised.

walk = os.walk(path2)

try:
    while True:
        dirpath, dirnames, filenames = next(walk)

        ... do something ...
except StopIteration:
    pass

Now if we go back to the other example:

curdir, dirlist, flist = os.walk(path2)

Then the above is the same as doing:

walk = os.walk(path2)
curdir = next(walk)
dirlist = next(walk)
flist = next(walk)

If the generator yields 3 or more values then that won't fail. If it however yields less than 3 values then it will fail, since there's less than 3 values to unpack.

So if the generator returned by os.walk() only yields a single value.

curdir, dirlist, flist = os.walk(path2)

Then the above will result in the following error:

ValueError: not enough values to unpack (expected 3, got 1)

If it's because you only need the first value, then go ahead and directly call next(). However be sure to catch any potential StopIteration.

try:
    curdir, dirlist, flist = next(os.walk(path2))
except StopIteration:
    pass

Lastly. Unless it's because you're utilizing dirlist and flist as an easy way to get the directories and files at a given path. Then you might not need os.walk and can instead just use os.listdir or os.scandir.

Upvotes: 2

wedi
wedi

Reputation: 1422

If I understand your question correctly what you want is not os.walk which outputs the list of files/directories in every subdirectory of path2 but os.scandir which lists all entries inside path2 itself.

Example from the docs linked above:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)

Upvotes: 0

Related Questions