0
def path(request, mypath):
    mypath = request.path_info
    _listdir = os.listdir(mypath)  # ['folder1', 'folder2', 'folder3', 'folder4']
    mess = _listdir
    a = ' '
    x=0
    scope = vars()  

    for i in mess:  
        scope['x']+=1  
        a += mess[x]
        a += '\n'

    return HttpResponse(a)

I hope the output is like this:

folder1
folder2
folder3
folder4

but why the output just like this:

folder1
folder1
folder1
folder1

any help?

1
  • What exactly are you trying to accomplish? Do you want a list of the folders? Commented Nov 12, 2010 at 6:55

5 Answers 5

4

There are huge swathes of unnecessary code in that function.

def path(request):
    return HttpResponse('\n'.join(os.listdir(request.path_info)))

Job done!

Sign up to request clarification or add additional context in comments.

Comments

3

From the docs:

Note: The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.

So, don't do that.

Comments

1
I hope the output is like this:

folder1
folder2
folder3
folder4

Thus shall you have your output...

for i in os.listdir(mypath):
    print i

You can return the i in the loop with HttpResponse there should be no problem, do this

returnString = ""
for i in os.listdir(mypath):
    returnString = returnString + i + "\n"

return returnString

1 Comment

@Johnsyweb What would a more "pythonic" version of such a code be?
1

You probably want

a += mess[i]

instead of

a += mess[x]

1 Comment

Doesn't make sense. mess[#] where # has to be an index, while the for i in loop returns strings.
1

Most of what you have is unneccesary. You just want to loop through the return values. Not modify them, nor play around with a variable indirectly via scope.

def path(request, mypath):
    mypath = request.path_info
    dirs = os.listdir(mypath)  # ['folder1', 'folder2', 'folder3', 'folder4']
    a = ''

    for i in dirs:  
        a += dirs
        a += '\n'

    return HttpResponse(a)

1 Comment

Not mess though in the for loop, but dirs... mess is undefined.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.