2014-02-11 194 views
0

我有我的code.The錯誤我得到一個特定的for循環的麻煩是「類型錯誤:強迫爲Unicode:需要字符串或緩衝區,列表中找到For循環Python的

我的代碼是:

current_dir = os. getcwd() 
target_dire = [os.listdir(current_dir)] 
for dirs in target_dirs: 
    if is.path.isdir(dirs): 
     print dirs[0] 

    else: 
     pass 

在此先感謝

+0

對不起我的手機搞砸代碼縮進 – Magicicada

+0

哪一行,你得到錯誤 – MONTYHS

+0

的,如果聲明行。 – Magicicada

回答

2

os#listdir已經返回一個列表,您不必再包裝它

從文檔:

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Source

若要將此到程序下面的代碼應該適合你的需求:

import os 

for dir in os.listdir(os.getcwd()): 
    if os.path.isdir(dir): 
     print dir 
+1

通過包裝在[]中,您正在創建一個dir條目列表列表。 for循環遍歷整個最外層列表,但dirs只是第二個內層列表。這將解決它。 –

+0

是的。這是故意的,因爲如果我不這樣做,它會打印列表中留下的第一個字母 – Magicicada

+0

@ user3295821請澄清您正在嘗試做什麼以獲得更多幫助。 – skuroda