Search code examples
pythonwindowsdirectory

Looping over subdirectories and their subdirectories and creating a dictionary


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.


Solution

  • 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.