开发者

How do I get names of subdirectories of a directory purely in python?

开发者 https://www.devze.com 2022-12-14 02:17 出处:网络
I dont want to u开发者_如何学Gose commands or any similar module that uses unix shell. Thanks in advance..Use os.walk():

I dont want to u开发者_如何学Gose commands or any similar module that uses unix shell. Thanks in advance..


Use os.walk():

import os, os.path

def walk_directories(src):
    for root, dirs, files in os.walk(src):
        for dir in dirs:
            print os.path.join(root, dir)

walk_directories(r'c:\temp')


If you want to do this recursively, going down a tree visiting all the directories, then you can use os.walk like this:

  for root, directories, files in os.walk("c:\\"):
    doSomething

If you only want the subdirectories you can either call walk once:

  directories = os.walk("c:\\").next()[1]

Or do some sort of filter like this (walk is more stylish/portable):

  filter(lambda x: os.path.isdir("c:\\"+ x), os.listdir("c:\\"))
0

精彩评论

暂无评论...
验证码 换一张
取 消