os.walk() ValueError: need more than 1 value to unpack

旧时模样 提交于 2019-11-30 20:35:57

os.walk returns an iterator that yields three-tuples, not a three-tuple:

for root, dirs, files in os.walk(top):
    # do stuff with root, dirs, and files

 

    In [7]: os.walk('.')
    Out[7]: <generator object walk at 0x1707050>

    In [8]: next(os.walk('.'))
    Out[8]:
    ('.',
     ['.vim',
      '.git',
       ...],
     ['.inputrc',
      ...])

You need to iterate over os.walk():

for root_o, dir_o, files_o in os.walk(top):

or store the iterator first, then loop:

walker = os.walk(top)
for root_o, dir_o, files_o in walker:

The return value of the callable is a generator function, and only when you iterate over it (with a for loop or by calling next() on the iterator) does it yield the 3-value tuples.

Try this

for root_o, dir_o, files_o in os.walk(top)
    print root_o, dir_o, files_o

os.walk is a generator and you need to iterate over it.

Perhaps what's more useful here is where it says "more than 1 value to unpack".

See, in python, you "unpack" a tuple (or list, as it may be) into the same number of variables:

a, b, c = (1, 2, 3)

There are a few different errors that turn up:

>>> a, b, c = (1, 2, 3, 4, 5, 6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

>>> a, b, c = (1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

Specifically, the last error is the type of error you're getting. os.walk() returns an iterator, i.e. a single value. You need to force that iterator to yield before it will start to give you values you can unpack!

This is the point of os.walk(); it forces you to loop over it, since it's attempting to walk! As such, the following snippet might work a little better for you.

for root_o, dir_o, files_o in os.walk(top):
    make_magic_happen(root_o, dir_o, files_o)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!