2014-02-11 193 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