2012-09-26 5 views
0

가능한 중복은 :
Create a tree-style directory listing in Python받기 파일 시스템 목록 파이썬

나는 파일 시스템을 분석하고 형식의 파일로 결과를 인쇄하고 싶습니다. 첫 번째 구현은 단순 텍스트 일 ​​수 있지만 나중에 HTML을 통합하려고합니다. 내가 돌아가서 텍스트 프로세서에 보낼 수있는 각 폴더에 포함 된 파일을 수집하는 기본적인 방법을 사용하고

: 분명히

def gather_tree(source): 
     tree = {} 
     for path, dirs, files in os.walk(source): 
      tree[path] = [] 
      for file in files: 
       tree[path].append(file) 
     return tree 

, 여기에 문제는 구조를 생산하고 있다는 점이다 그 적절한 공간과 중첩으로 목록을 올바르게 포맷 할 수 있어야한다고 생각하는 깊이 개념이 없습니다.

내 현재 아주 기본적인 인쇄 패턴은 다음과 같습니다

def print_file_tree(tree): 
    # Prepare tree 
    dir_list = tree.keys() 
    dir_list.sort() 

    for directory in dir_list: 
     print directory 
     for f in tree[directory]: 
      print f 

내가 데이터 구조 종류의 새로운 오전 일부 입력을 부탁드립니다!

+0

글쎄, 당신의 나무가 정말 나무 아니다 :) 나무는 ** 부모 ** 및 ** 어린이 **를 가진 ** 노드 **로 구성됩니다. Wikipedia의 [그래프 이론]에 대한 기사 (http://en.wikipedia.org/wiki/Graph_theory)는 좋은 읽을 거리가 될 것입니다. 그러나 가장 적합한 데이터 구조는 데이터로 무엇을하고 싶은지에 달려 있습니다. 아마도 트리가 필요하지 않을 수도 있습니다. 텍스트 프로세서는 어떤 종류의 작업을 수행합니까? –

+0

먼저 XML 및 HTML과 같은 적절한 형식으로 파일을 인쇄 할 수 있어야합니다. 그런 다음 라이징에 포함 된 파일 유형에 대한 정보를 수집하고 싶습니다. –

+0

다음 이것은 밀접하게 [이 질문에] 관련이있는 것 같다 (http://stackoverflow.com/questions/2104997/os-walk-python-xml-representation-of-a-directory-structure-recursion) (비록 XML 트리 생성에 [lxml] (http://lxml.de/)을 사용하십시오. –

답변

2

데이터에서 XML을 만들 계획이라면 실제로는 나무와 같은 구조를 만들어야합니다. 이 트리는 빌드, 주석 달기 및 반복 가능한 반복 또는 트래버스를 수행하는 중간 트리가 될 수 있으며 XML을 작성하기 위해 ElementTree으로 변환 할 수 있습니다. 또는 lxml의 ElementTree API를 사용하여 ElementTree을 직접 생성 할 수 있습니다.

어느 쪽이든, os.walk()을 사용하면 갈 길이 없습니다. 이것은 반 직관적으로 들릴지 모르겠지만 요점은 다음과 같습니다. os.walk()은 파일 시스템 트리를 직렬화 (평평하게)하므로 쉽게 반복 할 수 있으며이를 수행하는 재귀 함수를 작성하지 않아도됩니다. 그러나 귀하의 경우 으로 트리 구조를 유지하고자하므로 직접 재귀 함수를 작성하는 것이 훨씬 쉽습니다.

을 사용하여 ElementTree을 빌드하는 방법의 예입니다.

import os 
from lxml import etree 


def dir_as_tree(path): 
    """Recursive function that walks a directory and returns a tree 
    of nested etree nodes. 
    """ 
    basename = os.path.basename(path) 
    node = etree.Element("node") 
    node.attrib['name'] = basename 
    # Gather some more information on this path here 
    # and write it to attributes 
    # ... 
    if os.path.isdir(path): 
     # Recurse 
     node.tag = 'dir' 
     for item in sorted(os.listdir(path)): 
      item_path = os.path.join(path, item) 
      child_node = dir_as_tree(item_path) 
      node.append(child_node) 
     return node 
    else: 
     node.tag = 'file' 
     return node 

# Create a tree of the current working directory 
cwd = os.getcwd() 
root = dir_as_tree(cwd) 

# Create an element tree from the root node 
# (in order to serialize it to a complete XML document) 
tree = etree.ElementTree(root) 

xml_document = etree.tostring(tree, 
           pretty_print=True, 
           xml_declaration=True, 
           encoding='utf-8') 
print xml_document 

예 출력 (이 코드는 느슨하게 비슷한 질문에 @MikeDeSimone's answer에 근거) : 이미 언급 한 바와 같이

<?xml version='1.0' encoding='utf-8'?> 
<dir name="dirwalker"> 
    <dir name="top1"> 
    <file name="foobar.txt"/> 
    <dir name="sub1"/> 
    </dir> 
    <dir name="top2"> 
    <dir name="sub2"/> 
    </dir> 
    <dir name="top3"> 
    <dir name="sub3"> 
     <dir name="sub_a"/> 
     <dir name="sub_b"/> 
    </dir> 
    </dir> 
    <file name="topfile1.txt"/> 
    <file name="walker.py"/> 
</dir>