Getting a list of all subdirectories in the current directory

后端 未结 29 2376
一个人的身影
一个人的身影 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:17

    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

    0 讨论(0)
  • 2020-11-22 08:19

    Thanks for the tips, guys. I ran into an issue with softlinks (infinite recursion) being returned as dirs. Softlinks? We don't want no stinkin' soft links! So...

    This rendered just the dirs, not softlinks:

    >>> import os
    >>> inf = os.walk('.')
    >>> [x[0] for x in inf]
    ['.', './iamadir']
    
    0 讨论(0)
  • 2020-11-22 08:21

    we can get list of all the folders by using os.walk()

    import os
    
    path = os.getcwd()
    
    pathObject = os.walk(path)
    

    this pathObject is a object and we can get an array by

    arr = [x for x in pathObject]
    
    arr is of type [('current directory', [array of folder in current directory], [files in current directory]),('subdirectory', [array of folder in subdirectory], [files in subdirectory]) ....]
    

    We can get list of all the subdirectory by iterating through the arr and printing the middle array

    for i in arr:
       for j in i[1]:
          print(j)
    

    This will print all the subdirectory.

    To get all the files:

    for i in arr:
       for j in i[2]:
          print(i[0] + "/" + j)
    
    0 讨论(0)
  • 2020-11-22 08:26

    I prefer using filter (https://docs.python.org/2/library/functions.html#filter), but this is just a matter of taste.

    d='.'
    filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d))
    
    0 讨论(0)
  • 2020-11-22 08:26

    Implemented this using python-os-walk. (http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/)

    import os
    
    print("root prints out directories only from what you specified")
    print("dirs prints out sub-directories from root")
    print("files prints out all files from root and directories")
    print("*" * 20)
    
    for root, dirs, files in os.walk("/var/log"):
        print(root)
        print(dirs)
        print(files)
    
    0 讨论(0)
  • 2020-11-22 08:27

    Copy paste friendly in ipython:

    import os
    d='.'
    folders = list(filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)))
    

    Output from print(folders):

    ['folderA', 'folderB']
    
    0 讨论(0)
提交回复
热议问题