[python] List Directories and get the name of the Directory

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 below and isn't working at the minute. I seem to be getting the parent folder name.

import os

for directories in os.listdir(os.getcwd()): 
    dir = os.path.join('/home/user/workspace', directories)
    os.chdir(dir)
    current = os.path.dirname(dir)
    new = str(current).split("-")[0]
    print new

I also have other files in the folder but I do not want to list them. I have tried the below code but I haven't got it working yet either.

for directories in os.path.isdir(os.listdir(os.getcwd())): 

Can anyone see where I am going wrong?

Thanks

Got it working but it seems a bit round about.

import os
os.chdir('/home/user/workspace')
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
    dir = os.path.join('/home/user/workspace', dirs)
    os.chdir(dir)
    current = os.getcwd()
    new = str(current).split("/")[4]
    print new

This question is related to python directory

The answer is


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


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.


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.