-3

How would I loop over subdirectories in a directory, returning them like this:

dirlist = {
  "area": ["square","circle"],
  "line": ["line"]
}

There's no need for fancy stuff, because I'm sure that there's only a subdirectory and a sub-subdirectory, nothing past that. There are multiple subdirectories and multiple sub-subdirectories for each subdirectory.

Veritius
  • 39
  • 1
  • 7
  • use ```os.walk()``` – ewokx Aug 06 '20 at 03:56
  • You do not have any directories. You have a dictionary. Each value in the dict contains a list. How do you iterate over a dict? This is in any tutorial on dicts -- along with how to access its value. Similarly, once you have that value, any tutorial on lists will teach you how to iterate over those. Where are you stuck? – Prune Aug 06 '20 at 03:57

1 Answers1

1

Link to half solution.

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

Other half is simple, you don't find a file as given in the link, you juts record the names of the subdirs in arr and the main subdir in as a key in dict, then to make the arr the value of key.

Nimantha
  • 6,405
  • 6
  • 28
  • 69