Python Source 디렉토리 구조 검색

입질쾌감 물때표
def ls(dir, hidden=False, relative=True):
    nodes = []
    for nm in os.listdir(dir):
        if not hidden and nm.startswith('.'):
        if not relative:
            nm = os.path.join(dir, nm)
    return nodes

def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True, self_check=False):
    root = os.path.join(root, '')  # add slash if not there
    for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
        if relative:
            parent = parent[len(root):]
        if dirs and parent:
            if root == os.path.join(parent, '') : continue
            yield os.path.join(parent, '')
        if not hidden:
            lfiles   = [nm for nm in lfiles if not nm.startswith('.')]
            ldirs[:] = [nm for nm in ldirs  if not nm.startswith('.')]  # in place
        if files:
            for nm in lfiles:
                nm = os.path.join(parent, nm)
                yield nm

def test(root):
    print "* directory listing, with hidden files:"
    print ls(root, hidden=True)
    print "* recursive listing, with dirs, but no hidden files:"
    for f in find(root, dirs=True):
        print f

관련 글

답글 남기기

이메일 주소는 공개되지 않습니다.