2010-11-12 53 views
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) 

我希望輸出是這樣的:爲什麼只是一個名稱可能採取

 
folder1 
folder2 
folder3 
folder4 

但爲什麼輸出就像這樣:

 
folder1 
folder1 
folder1 
folder1 

任何幫助嗎?

+0

你究竟在做什麼?你想要一個文件夾列表嗎? – soulseekah 2010-11-12 06:55:25

回答

1
I hope the output is like this: 

folder1 
folder2 
folder3 
folder4 

因此,你應該有你的輸出...

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

您可以用HttpResponse循環returni應該沒有問題,這樣做

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

return returnString 
+0

謝謝你,好工作。 – 2010-11-12 07:17:38

+0

雖然這可行,但它不是很「pythonic」。 – Johnsyweb 2010-11-12 16:33:05

+0

@Johnsyweb這樣的代碼更「pythonic」版本會是什麼? – soulseekah 2010-11-12 16:35:59

1

你可能想

a += mess[i] 

,而不是

a += mess[x] 
+0

沒有意義。 'mess [#]'其中#必須是索引,而'for in循環返回字符串。 – soulseekah 2010-11-12 06:54:34

+0

對,我太快了。 – mjhm 2010-11-12 07:31:51

3

the docs

注:返回的字典不應進行修改:在相應的符號的影響表是未定義的。

所以,不要這樣做。

1

你所擁有的大部分是無用的。你只是想循環返回值。不要修改它們,也不要通過範圍間接使用變量。

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) 
+0

雖然在for循環中沒有'mess',但'dirs' ...'mess'是未定義的。 – soulseekah 2010-11-12 07:07:35

+1

謝謝。修復。 – wnoise 2010-11-12 07:47:34

4

該函數中有大量不必要的代碼。

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

工作完成!

+1

不錯!肯定更多Pythonic ... – soulseekah 2010-11-12 16:38:37

相關問題