Getting a list of all subdirectories in the curren

2018-12-31 19:53发布

Is there a way to return a list of all the subdirectories in the current directory in Python?

I know you can do this with files, but I need to get the list of directories instead.

21条回答
查无此人
2楼-- · 2018-12-31 20:07

Here are a couple of simple functions based on @Blair Conrad's example -

import os

def get_subdirs(dir):
    "Get a list of immediate subdirectories"
    return next(os.walk(dir))[1]

def get_subfiles(dir):
    "Get a list of immediate subfiles"
    return next(os.walk(dir))[2]
查看更多
人间绝色
3楼-- · 2018-12-31 20:10

If you need a recursive solution that will find all the subdirectories in the subdirectories, use walk as proposed before.

If you only need the current directory's child directories, combine os.listdir with os.path.isdir

查看更多
裙下三千臣
4楼-- · 2018-12-31 20:10

Building upon Eli Bendersky's solution, use the following example:

import os
test_directory = <your_directory>
for child in os.listdir(test_directory):
    test_path = os.path.join(test_directory, child)
    if os.path.isdir(test_path):
        print test_path
        # Do stuff to the directory "test_path"

where <your_directory> is the path to the directory you want to traverse.

查看更多
琉璃瓶的回忆
5楼-- · 2018-12-31 20:11

Python 3.4 introduced the pathlib module into the standard library, which provides an object oriented approach to handle filesystem paths:

from pathlib import Path

p = Path('./')

# List comprehension
[f for f in p.iterdir() if f.is_dir()]

# The trailing slash to glob indicated directories
# This will also include the current directory '.'
list(p.glob('**/'))

Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.

查看更多
泪湿衣
6楼-- · 2018-12-31 20:12

Since I stumbled upon this problem using Python 3.4 and Windows UNC paths, here's a variant for this environment:

from pathlib import WindowsPath

def SubDirPath (d):
    return [f for f in d.iterdir() if f.is_dir()]

subdirs = SubDirPath(WindowsPath(r'\\file01.acme.local\home$'))
print(subdirs)

Pathlib is new in Python 3.4 and makes working with paths under different OSes much easier: https://docs.python.org/3.4/library/pathlib.html

查看更多
一个人的天荒地老
7楼-- · 2018-12-31 20:12

I've had a similar question recently, and I found out that the best answer for python 3.6 (as user havlock added) is to use os.scandir. Since it seems there is no solution using it, I'll add my own. First, a non-recursive solution that lists only the subdirectories directly under the root directory.

def get_dirlist(rootdir):

    dirlist = []

    with os.scandir(rootdir) as rit:
        for entry in rit:
            if not entry.name.startswith('.') and entry.is_dir():
                dirlist.append(entry.path)

    dirlist.sort() # Optional, in case you want sorted directory names
    return dirlist

The recursive version would look like this:

def get_dirlist(rootdir):

    dirlist = []

    with os.scandir(rootdir) as rit:
        for entry in rit:
            if not entry.name.startswith('.') and entry.is_dir():
                dirlist.append(entry.path)
                dirlist += get_dirlist(entry.path)

    dirlist.sort() # Optional, in case you want sorted directory names
    return dirlist

keep in mind that entry.path wields the absolute path to the subdirectory. In case you only need the folder name, you can use entry.name instead. Refer to os.DirEntry for additional details about the entry object.

查看更多
登录 后发表回答