How to parse a directory tree in python?

You could utilize os.walk.

#!/usr/bin/env python

import os
for root, dirs, files in os.walk('notes'):
    print(root, dirs, files)

Naive two level traversing:

import os
from os.path import isdir, join

def cats_and_subs(root='notes'):
    """
    Collect categories and subcategories.
    """
    categories = filter(lambda d: isdir(join(root, d)), os.listdir(root))
    sub_categories = []
    for c in categories:
        sub_categories += filter(lambda d: isdir(join(root, c, d)), 
            os.listdir(join(root, c)))
    
    # categories and sub_categories are arrays,
    # categories would hold stuff like 'science', 'maths'
    # sub_categories would contain 'Quantum Mechanics', 'Linear Algebra', ...
    return (categories, sub_categories)

if __name__ == '__main__':
    print(cats_and_subs(root='/path/to/your/notes'))

Tags:

Python