如何在python中解析目录树?

时间:2010-05-29 23:10:45

标签: python

我在笔记中有一个名为“notes”的目录,我有类别名为“science”,“maths”......在这些文件夹中是子类别,例如“Quantum Mechanics”,“Linear Algebra”。

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

我的问题是我不知道如何将类别和子类别放入两个单独的列表/数组中。

2 个答案:

答案 0 :(得分:15)

您可以使用os.walk

#!/usr/bin/env python

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

天真的两级遍历:

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 :(得分:1)

os.walk非常适合这个。默认情况下,它会执行自上而下的步行,您可以通过设置'dirnames'在第2级轻松终止它,在此时为空。

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)