tags:

views:

560

answers:

2

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.

+7  A: 
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
Adam Rosenfield
What I want do do is create 1 level of a file tree (the root directory, the folders inside, and the files) and pass those values to the template at the end.
+1  A: 

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.

tgray