Getting a list of all subdirectories in the current directory

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

提交回复
热议问题