Getting a list of all subdirectories in the current directory

后端 未结 29 2835
一个人的身影
一个人的身影 2020-11-22 08:02

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 direct

29条回答
  •  暖寄归人
    2020-11-22 08:33

    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('./')
    
    # All subdirectories in the current directory, not recursive.
    [f for f in p.iterdir() if f.is_dir()]
    

    To recursively list all subdirectories, path globbing can be used with the ** pattern.

    # This will also include the current directory '.'
    list(p.glob('**'))
    

    Note that a single * as the glob pattern would include both files and directories non-recursively. To get only directories, a trailing / can be appended but this only works when using the glob library directly, not when using glob via pathlib:

    import glob
    
    # These three lines return both files and directories
    list(p.glob('*'))
    list(p.glob('*/'))
    glob.glob('*')
    
    # Whereas this returns only directories
    glob.glob('*/')
    

    So Path('./').glob('**') matches the same paths as glob.glob('**/', recursive=True).

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

提交回复
热议问题