drillau
drillau

Reputation: 25

How to get different lists of file paths depending on subdirs?

-Root
--A
---1,2
--B
---3

I am trying to get a list of lists of paths based on subdirs:

[['Root/A/1','Root/A/2'],['Root/B/3']]

I tried using os.walk but I couldn't get it to work. I can get a list of all files in one giant list but I can't split those based on subdirs

fullList = []
for root, dirs, files in os.walk(dir):
        for name in files:
            fullList.append(os.path.join(root, name))

Upvotes: 0

Views: 53

Answers (1)

Robᵩ
Robᵩ

Reputation: 168616

You want to have a list of lists, but you create a list of strings. You'll need to create each of the interior lists and put them all together into one master list.

This program might do what you want:

import os
from pprint import pprint


def return_list_of_paths(dir='.'):
    return [[os.path.join(root, file) for file in files]
            for root, dirs, files in os.walk(dir)
            if files]


pprint(return_list_of_paths("ROOT"))

Or, if you don't care for list comprehensions:

import os
from pprint import pprint


def return_list_of_paths(dir='.'):
    fullList = []
    for root, dirs, files in os.walk(dir):
        if files:
            oneList = []
            for file in files:
                oneList.append(os.path.join(root, file))
            fullList.append(oneList)
    return fullList


pprint(return_list_of_paths("ROOT"))

Upvotes: 1

Related Questions