【问题标题】:For loop Python对于循环 Python
【发布时间】:2014-02-11 06:03:17
【问题描述】:

我的代码中的特定 for 循环出现问题。我得到的错误是“TypeError: coercing to Unicode: need string or buffer, list found

我的代码是:

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

提前致谢

【问题讨论】:

  • 抱歉我的手机弄乱了代码缩进
  • 哪一行出错
  • if 语句行。
  • 打印目录或查看目录类型

标签: python-2.7 for-loop


【解决方案1】:

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

【讨论】:

  • 通过包装[],您正在创建一个目录条目列表。 for 循环遍历最外层列表,但 dirs 只是第二个内部列表。这将解决它。
  • 是的。这是故意的,因为如果我不这样做,它将打印出列表中剩余内容的第一个字母
  • @user3295821 请说明您想要做什么以获得更多帮助。
  • 这是因为print dirs[0]。字符串只是 Python 中的列表或字符(从技术上讲,这不是真的,但这是推理此代码的一种简单方法)。将其更改为print dirs
  • 如果我给它一个特定的偏移量,它就可以工作,但我希望它迭代整个列表。
猜你喜欢
  • 2016-06-06
  • 2021-12-16
  • 2016-01-24
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
相关资源
最近更新 更多