List Directories and get the name of the Directory

前端 未结 4 949
再見小時候
再見小時候 2020-12-29 00:57

I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is belo

相关标签:
4条回答
  • 2020-12-29 01:21
    import os
    for root, dirs, files in os.walk(top, topdown=False):
        for name in dirs:
            print os.path.join(root, name)
    

    Walk is a good built-in for what you are doing

    0 讨论(0)
  • 2020-12-29 01:24

    Listing the entries in the current directory (for directories in os.listdir(os.getcwd()):) and then interpreting those entries as subdirectories of an entirely different directory (dir = os.path.join('/home/user/workspace', directories)) is one thing that looks fishy.

    0 讨论(0)
  • 2020-12-29 01:25

    You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()

    For example, as explained here: [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively.

    0 讨论(0)
  • 2020-12-29 01:29

    This will print all the subdirectories of the current directory:

    print [name for name in os.listdir(".") if os.path.isdir(name)]
    

    I'm not sure what you're doing with split("-"), but perhaps this code will help you find a solution?

    If you want the full pathnames of the directories, use abspath:

    print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]
    

    Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk as others have suggested.

    0 讨论(0)
提交回复
热议问题