2012-06-09 6 views
15

html 문서를 생성하는 데 Python을 사용하는 데 몇 가지 문제가 있습니다. 디렉터리 트리의 HTML 목록을 만들려고합니다. 이것은 내가 지금까지 가지고있는 것입니다 :Python을 사용하여 html 디렉토리 목록을 생성하는 방법

def list_files(startpath): 
    for root, dirs, files in os.walk(startpath): 
     level = root.replace(startpath, '').count(os.sep) 
     if level <= 1: 
      print('<li>{}<ul>'.format(os.path.basename(root))) 
     else: 
      print('<li>{}'.format(os.path.basename(root))) 
     for f in files: 
      last_file = len(files)-1 
      if f == files[last_file]: 
       print('<li>{}</li></ul>'.format(f)) 
      elif f == files[0] and level-1 > 0: 
       print('<ul><li>{}</li>'.format(f)) 
      else: 
       print('<li>{}</li>'.format(f)) 
    print('</li></ul>') 

루트 디렉토리, 하위 디렉토리 및 파일의 한 수준 만 있으면 제대로 작동하는 것 같습니다. 그러나 다른 수준의 하위 디렉토리를 추가하면 문제가 발생합니다 (닫기 태그가 내가 생각하는 끝에 충분한 시간이 입력되지 않았기 때문에). 그러나 나는 그 주위에 머리를 쓰는 데 어려움을 겪고있다.

이렇게 할 수 없다면 더 쉬운 방법이 있을까요? 저는 플라스크를 사용하고 있습니다 만, 템플릿이 매우 익숙하지 않아서 뭔가 빠져 있습니다.

+3

[플라스크-자동 색인은] (http://packages.python.org/Flask-AutoIndex/) – jfs

답변

34

디렉토리 트리 생성과 렌더링을 html로 구분할 수 있습니다.

<!doctype html> 
<title>Path: {{ tree.name }}</title> 
<h1>{{ tree.name }}</h1> 
<ul> 
{%- for item in tree.children recursive %} 
    <li>{{ item.name }} 
    {%- if item.children -%} 
     <ul>{{ loop(item.children) }}</ul> 
    {%- endif %}</li> 
{%- endfor %} 
</ul> 

templates/dirtree.html 파일에 HTML을 넣어 :

def make_tree(path): 
    tree = dict(name=os.path.basename(path), children=[]) 
    try: lst = os.listdir(path) 
    except OSError: 
     pass #ignore errors 
    else: 
     for name in lst: 
      fn = os.path.join(path, name) 
      if os.path.isdir(fn): 
       tree['children'].append(make_tree(fn)) 
      else: 
       tree['children'].append(dict(name=name)) 
    return tree 

당신이 jinja2의 루프 recursive 기능을 사용할 수 있습니다 HTML로 렌더링하려면 :

는 간단한 재귀 함수를 사용할 수있는 트리를 생성합니다. 이를 테스트하려면 다음 코드를 실행하고 http://localhost:8888/를 방문하십시오

import os 
from flask import Flask, render_template 

app = Flask(__name__) 

@app.route('/') 
def dirtree(): 
    path = os.path.expanduser(u'~') 
    return render_template('dirtree.html', tree=make_tree(path)) 

if __name__=="__main__": 
    app.run(host='localhost', port=8888, debug=True) 
+0

을이 완벽하게 작동합니다. – bem3ry

+0

훌륭한 솔루션입니다. 감사. – under5hell

+0

진자에 익숙하지 않다면'dirtree.html' 템플릿 파일은'templates' 디렉토리에 있어야합니다. –

관련 문제