了解python中的变量赋值

我是菜鸟,正在尝试了解Python。


对于os.walk文档,它说它返回一个元组(dirpath,dirnames,filenames)


只是理解,我试图像下面一样使用它


import os

from os.path import join, getsize

file=[]

dir=[]

xroot,dir,file = os.walk('C:\Python27\mycode')

但这给了我这样的错误:xroot,dir,file = os.walk('C:\ Python27 \ mycode')ValueError:需要两个以上的值来解压


我的问题是为什么我不能像上面那样分配它,而是让它成为循环的一部分(大多数示例使用它)?


临摹微笑
浏览 170回答 3
3回答

郎朗坤

os.walk返回一个迭代器。通常认为要做的就是遍历它for xroot, dir, file in os.walk('C:\Python27\mycode'):     ...但您也可以只使用xroot, dir, file = next(os.walk('C:\Python27\mycode'))单步执行

守着一只汪

os.walk不返回root,dir,file。它返回一个生成器对象供程序员循环。很可能是因为给定路径可能包含子目录,文件等。>>> import os>>> xroot,dir,file = os.walk('/tmp/') #this is wrong.Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>ValueError: too many values to unpack>>> os.walk('/tmp/')<generator object walk at 0x109e5c820> #generator object returned, use it>>> for xroot, dir, file in os.walk('/tmp/'):...&nbsp; &nbsp; &nbsp;print xroot, dir, file...&nbsp;/tmp/ ['launched-IqEK']/tmp/launch-IqbUEK [] ['foo']/tmp/launch-ldsaxE [] ['bar']>>>&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python