2010-05-29 44 views
9

Tôi có một thư mục được gọi là "ghi chú" trong các ghi chú tôi có các danh mục được đặt tên là "khoa học", "toán học" ... trong thư mục đó là các danh mục phụ, chẳng hạn như "Cơ học lượng tử", "Đại số tuyến tính".Cách phân tích cú pháp cây thư mục trong python?

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

Vấn đề của tôi là tôi không biết cách đặt danh mục và danh mục con vào HAI danh sách/mảng riêng biệt.

+1

Bạn muốn đọc chúng thành gì? một danh sách lồng nhau, một từ điển chứa danh sách? –

Trả lời

13

Bạn có thể sử dụng os.walk.

#!/usr/bin/env python 

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

Naive hai mức 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') 
1

os.walk là khá nhiều lý tưởng cho việc này. Theo mặc định, nó sẽ thực hiện một bước đi từ trên xuống, và bạn có thể chấm dứt nó dễ dàng ở cấp độ 2 bởi các thiết lập 'dirnames' được để trống tại thời điểm đó.

import os 
pth = "/path/to/notes" 
def getCats(pth): 
    cats = [] 
    subcats = [] 
    for (dirpath, dirnames, filenames) in os.walk(pth): 
     #print dirpath+"\n\t", "\n\t".join(dirnames), "\n%d files"%(len(filenames)) 
     if dirpath == pth: 
      cats = dirnames 
     else: 
      subcats.extend(dirnames) 
      dirnames[:]=[] # don't walk any further downwards 
    # subcats = list(set(subcats)) # uncomment this if you want 'subcats' to be unique 
    return (cats, subcats) 
Các vấn đề liên quan