Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a directory tree in python?

Tags:

python

I have a directory called "notes" within the notes I have categories which are named "science", "maths" ... within those folder are sub-categories, such as "Quantum Mechanics", "Linear Algebra".

./notes
--> ./notes/maths
------> ./notes/maths/linear_algebra
--> ./notes/physics/
------> ./notes/physics/quantum_mechanics

My problem is that I don't know how to put the categories and subcategories into TWO SEPARATE list/array.

like image 367
chutsu Avatar asked May 29 '10 23:05

chutsu


People also ask

How do I show a directory tree in Python?

Practical Data Science using Python You can use the os. walk() method to get the list of all children of path you want to display the tree of. Then you can join the paths and get the absolute path of each file.

What does parse () do in Python?

In this article, parsing is defined as the processing of a piece of python program and converting these codes into machine language. In general, we can say parse is a command for dividing the given program code into a small piece of code for analyzing the correct syntax.


1 Answers

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'))
like image 89
miku Avatar answered Oct 25 '22 09:10

miku