简体   繁体   中英

Python value unpacking error

I'm building a per-user file browsing/uploading application using Django and when I run this function


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. 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 . However, your walktoo function is a generator object: calling walktoo() yields a single value, the generator. 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.

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() . 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).

path, dirs, files = [_ for _ in os.walk('/home/damon/walktemp/%s' % path)][0]

This is as an alternative to your walktoo(dir) funciton.

Also, make sure your second parameter to render_to_response uses the variables you created:

{'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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM