Getting a list of all subdirectories in the current directory

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

    Although this question is answered a long time ago. I want to recommend to use the pathlib module since this is a robust way to work on Windows and Unix OS.

    So to get all paths in a specific directory including subdirectories:

    from pathlib import Path
    paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))
    
    # all sorts of operations
    file = paths[0]
    file.name
    file.stem
    file.parent
    file.suffix
    

    etc.

提交回复
热议问题