0

I'm able to list the directories and files using the below code

for root, dirs, files in os.walk(startpath):
    level = root.replace(startpath, '').count(os.sep)
    indent = ' ' * 4 * (level)
    print('Directory -> {}{}/'.format(indent, os.path.basename(root)))
    subindent = ' ' * 4 * (level + 1)
    for f in files:
        if not f.startswith('.'):
            print('file -> {}{}'.format(subindent, f))

I need only directories and nested directories to be stored in a format so that I can show that on UISample folder tree

Krishna
  • 1,089
  • 5
  • 24
  • 38
  • 1
    I'm unsure what you're trying to achieve? Are you looking for a text output that is similar to the above picture? – ScottMcC Jul 06 '18 at 06:05
  • I need a list of dicts or list of lists having the hierarchy of the directories so that I can use that and generate a tree structure on UI – Krishna Jul 06 '18 at 06:08
  • https://stackoverflow.com/questions/39327032/how-to-get-the-latest-file-in-a-folder-using-python/39327156#39327156 This may be helpful – Marlon Abeykoon Jul 06 '18 at 06:10

1 Answers1

0

Use the os.listdir() function from the os package to list all files and directories at your location.

import os
onlyfiles = [f for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]
onlydir = [dir for dir in os.listdir(mypath) if os.path.isdir(os.path.join(mypath, dir))]

Then you can change to other directories with os.chdir(onlydir[i]) where you can do the same stuff to collect all files and directories.

dl.meteo
  • 1,658
  • 15
  • 25
  • 1
    there is an error here `os.isdir(join` Undefined variable: join, undefined variable from import: isdir – Krishna Jul 06 '18 at 07:13