[英]Python value unpacking error
I'm building a per-user file browsing/uploading application using Django and when I run this function 我正在使用Django构建每用户文件浏览/上传应用程序,并且在运行此功能时
def walkdeep(request, path):
path, dirs, files = walktoo('/home/damon/walktemp/%s' % path)
return render_to_response('walk.html', {
'path' : path[0],
'dirs' : path[1],
'files' : path[2],
}, context_instance=RequestContext(request))
def walktoo(dir):
for path, dirs, files in os.walk(dir):
yield path, dirs, files
print path, dirs, files
I get this error: 我收到此错误:
need more than 1 value to unpack
Also, i know this is a silly way to do this, any advice would be appreciated. 另外,我知道这是一种愚蠢的方式,任何建议将不胜感激。
edit: 编辑:
this was actually very silly on my part, i completely forgot about os.listdir(dir) which is a much more reasonable function for my purposes. 这对我来说实际上是很愚蠢的,我完全忘记了os.listdir(dir),这对于我来说是一个更合理的功能。 if you use the selected answer, it clears up the above issue i was having, but not with the results i wanted.
如果使用选定的答案,它将清除我遇到的上述问题,但不会消除我想要的结果。
path, dirs, files = walktoo('/home/damon/walktemp/%s' % path)
In this line, you're expecting walktoo
to return a tuple of three values, which are then to be unpacked into path
, dirs
, and files
. 在这一行中,您期望
walktoo
返回三个值的元组,然后将其解压缩为path
, dirs
和files
。 However, your walktoo
function is a generator object: calling walktoo()
yields a single value, the generator. 但是,
walktoo
函数是一个生成器对象:调用walktoo()
生成一个值,即生成器。 You have to call next()
on the generator (or call it implicitly by doing some sort of iteration on it) to get what you actually want, namely the 3-tuple that it yields. 您必须在生成器上调用
next()
(或通过对其进行某种形式的迭代来隐式调用)以获取实际所需的内容,即生成的3元组。
I'm not entirely clear what you want to do -- your walkdeep()
function is written like it only wants to use the first value returned by walktoo()
. 我尚不清楚您要做什么-您的
walkdeep()
函数的编写就像只想使用walktoo()
返回的第一个值walktoo()
。 Did you mean to do something like this? 你是说要做这样的事吗?
for path, dirs, files in walktoo(...):
# do something
Based on your comment to Adam Rosenfield , this is another approach to get one layer of os.walk(dir). 根据您对Adam Rosenfield的评论,这是获取一层os.walk(dir)的另一种方法。
path, dirs, files = [_ for _ in os.walk('/home/damon/walktemp/%s' % path)][0]
This is as an alternative to your walktoo(dir) funciton. 这是walktoo(dir)函数的替代方法。
Also, make sure your second parameter to render_to_response
uses the variables you created: 另外,请确保您的
render_to_response
的第二个参数使用您创建的变量:
{'path' : path,
'dirs' : dirs,
'files' : files,}
path
is a string, so by saying path[0]
... path[1]
... path[2]
you're actually saying to use the first, second, and third character of the string. path
是一个字符串,因此说出path[0]
... path[1]
... path[2]
实际上是在说使用字符串的第一个,第二个和第三个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.