How to list only top level directories in Python?

前端 未结 18 1446
既然无缘
既然无缘 2020-12-04 07:51

I want to be able to list only the directories inside some folder. This means I don\'t want filenames listed, nor do I want additional sub-folders.

Let\'s see if an

18条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 08:42

    being a newbie here i can't yet directly comment but here is a small correction i'd like to add to the following part of ΤΖΩΤΖΙΟΥ's answer :

    If you prefer full pathnames, then use this function:

    def listdirs(folder):  
      return [
        d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
        if os.path.isdir(d)
    ]
    

    for those still on python < 2.4: the inner construct needs to be a list instead of a tuple and therefore should read like this:

    def listdirs(folder):  
      return [
        d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]
        if os.path.isdir(d)
      ]
    

    otherwise one gets a syntax error.

提交回复
热议问题