8

This is my code :

import os

def get_file():
    files = os.listdir('F:/Python/PAMC')
    print(files)

    for file in files:
        print(file)

get_file()

How do i list only folders in a directory in python?

MOHS3N
  • 229
  • 1
  • 4
  • 13

3 Answers3

20

Tried and tested the below code in Python 3.6

import os

filenames= os.listdir (".") # get all files' and folders' names in the current directory

result = []
for filename in filenames: # loop through all the files and folders
    if os.path.isdir(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a folder or not
        result.append(filename)

result.sort()
print(result)

#To save Foldes names to a file.
f= open('list.txt','w')
for index,filename in enumerate(result):
    f.write("%s. %s \n"%(index,filename))

f.close()

Alternative way:

import os
for root, dirs, files in os.walk(r'F:/Python/PAMC'):
    print(root)
    print(dirs)
    print(files)

Alternative way

import os
next(os.walk('F:/Python/PAMC'))[1]
Ramineni Ravi Teja
  • 3,568
  • 26
  • 37
6

Try a generator with os.walk to get all folders in the specified directory:

next(os.walk('F:/Python/PAMC'))[1]
Austin
  • 25,759
  • 4
  • 25
  • 48
1

If you want the folder names using a for loop, you can use the following code.

#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Using 'yield' to get folder names in a directory
#--------*---------*---------*---------*---------*---------*---------*---------*

import os
import sys

def find_folders():
    for item in os.listdir():
        if os.path.isfile(item):
            continue
        else:
#                                  # yield folder name     
            yield item


#--------*---------*---------*---------*---------*---------*---------*---------#
while 1:#                          M A I N L I N E                             #
#--------*---------*---------*---------*---------*---------*---------*---------#
#                                  # set directory
    os.chdir("C:\\Users\\Mike\\Desktop")
    for folder in find_folders():
         print (folder)
    sys.exit()                     # END SAMPLE CODE SNIPPET
CopyPasteIt
  • 532
  • 1
  • 8
  • 22