List Directories and get the name of the Directory

Posted by chrissygormley on Stack Overflow See other posts from Stack Overflow or by chrissygormley
Published on 2010-04-22T11:29:29Z Indexed on 2010/04/22 11:33 UTC
Read the original article Hit count: 274

Filed under:
|

Hello,

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

© Stack Overflow or respective owner

Related posts about python

Related posts about directories